0
int train [4] [3] = {   0, 0, 0,
                                      0, 1, 0,
                                      1, 0, 0,
                                      1, 1, 1 };

Is that a valid initialization of a 2d array in C++

And the rows will be 0,0,0 (row 1), (0,1,0) (row2), (1,0,0) (row3) and (1,1,1) (row 4) ?

And is it equivalent to

 int train [4] [3] = {{0, 0, 0},
                       {0, 1, 0},
                       {1, 0, 0},
                       {1, 1, 1}};
2
  • 3
    Why just write the equivalent version - as it works!
    – Ed Heal
    Commented Nov 22, 2015 at 7:09
  • 10
    It should be very easy to check, wouldn't it? Commented Nov 22, 2015 at 7:11

2 Answers 2

7
int train [4] [3] = {   0, 0, 0,
                        0, 1, 0,
                        1, 0, 0,
                        1, 1, 1 };

is a valid initialization of a 2D array in C++.

From the C++11 Standard:

8.5.1 Aggregates

10 When initializing a multi-dimensional array, the initializer-clauses initialize the elements with the last (right-most) index of the array varying the fastest (8.3.4). [ Example:

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

initializes x[0][0] to 3, x[0][1] to 1, x[1][0] to 4, and x[1][1] to 2. On the other hand,

float y[4][3] = {
  { 1 }, { 2 }, { 3 }, { 4 }
};

initializes the first column of y (regarded as a two-dimensional array) and leaves the rest zero. — end example ]

3

Yes! It is a valid intialization in c++.

Not the answer you're looking for? Browse other questions tagged or ask your own question.