Section 24.3 Initializing Multidimensional Arrays
It is possible to initialize a multidimensional array during declaration time. In fact, there are multiple ways to do so. The following four ways are actually all equivalent and all initialize a 2-dimensional array with the same values:
int matrix1[NROWS][NCOLS] = {{1,2}, {3,4}, {5,6}, {7,8} };
int matrix2[NROWS][NCOLS] = { {1,2},
{3,4},
{5,6},
{7,8}};
int matrix3[][NCOLS] = {{1,2}, {3,4}, {5,6}, {7,8} };
int matrix4[][NCOLS] = {1, 2, 3, 4, 5, 6, 7, 8};
The Codecast below illustrates this further:
If you cannot see this codecast, please click here .
Aside: Video Description.
Multidimensional arrays can be initialized by enclosing values in (nested) curly brackets: {}
i.e. int matrix[4][2] = {{1,2}, {3,4}, {5,6}, {7,8}};
Check Your Understanding Check Your Understanding
1.
Which of the following is correct?
int matrix[][2] = {5, 2, 7, 5, 3, 2, 8, 6};
Correct
int matrix[4][] = {5, 2, 7, 5, 3, 2, 8, 6};
Not quite. Try again!
int matrix = {5, 2, 7, 5, 3, 2, 8, 6};
Not quite. Try again!
int matrix[][] = {5, 2, 7, 5, 3, 2, 8, 6};
Not quite. Try again!