简体   繁体   中英

Unexpected Initializing outcome from 2D array

To initialize a 2D array, usually we can do it like this:

int matrix[3][4] = { {1,1,1,1}, {2,2,2,2}, {3,3,3,3} };

However, as I was testing it with various combinations, the following codes did compile out of my expectation:

int matrix[3][4] = {1,2,3,4,5,6,7};

When I print out the output in a 2D-table form, I get:

1,2,3,4,
5,6,7,0,
0,0,0,0,

I understand why the rest of the values are zeroes.

My question is : Is this one of the legitimate ways to initialize 2D array by assuming the numbers which exceed the bounds of a row will always "flow" to the next row? Or is this another pitfall I should avoid in C++ ?

Yes, this is perfectly fine. Quoting the unofficial cppreference :

The braces around the nested initializer lists may be elided (omitted), in which case as many initializer clauses as necessary are used to initialize every member or element of the corresponding subaggregate, and the subsequent initializer clauses are used to initialize the following members of the object.

And:

If the number of initializer clauses is less than the number of members or initializer list is completely empty, the remaining members are initialized by empty lists, which performs value-initialization.

And value initializing an int sets it to 0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM