There are a few key points you need to remember if you want to deal with arrays of arrays.
- An array holds only one type of data.
- cells of the arrays are contiguous in memory, starting with the one at index 0.
- a 2D array is a 1D array of 1D arrays of the underlying type.
- When passed "naked" to a function, an arrays decays to the pointer to the first element in the array
So, in C++, when you write something like:
char matrix[3][4];
You're declaring a 2D array and you can see that as three rows and four columns, and here's what that really means in C++:
matrix is an array of 3 elements.
- Each of those 3 elements is itself an array of 4
chars.
- So the type of
matrix is char[3][4]
- The type of
matrix[0] is char[4]
- The type of
matrix[0][0] is char
And the memory layout is where people sometimes get confused:
- The data is still stored contiguously in memory, like a flat array of 12
chars.
- But syntactically and semantically, C++ still treats it as an array of arrays.
- That affects how pointers work: if you write
char (*p)[4] = matrix;, p is a pointer to an array of 4 char (i.e., one row). You can then do p + 1 to go to the next row.
So it’s not just a flat 1D array of 12 chars — it really is structured as arrays of arrays.
In theory you should write
char matrix1[3][4] = {
{'A', 'B', 'C', 'D'},
{'E', 'F', 'G', 'H'},
{'I', 'J', 'K', 'L'}
};
This clearly shows that matrix[0] which type is char[4] has to be initialized with an array of 4 chars, and this is what you pass {'A', 'B', 'C', 'D'}
Where it gets somewhat confusing is that the compiler knows how to arrange data in memory sequentially when passed an initial value. So if you write
char matrix2[3][4] = {'A','B','C','D','E','F','G','H','I','J','K','L'};
the compiler will be fine and it's the same array. You're just providing a flat list of 12 characters; the compiler fills the array row by row (known as "row-major order"), so it works the same way: the initialiser list is simply unrolled across the array dimensions in the order they appear.
As long as the number of elements matches 3 × 4 = 12, both forms are correct.