Two-Dimensional Arrays
A two-dimensional array is an array of arrays. Rows and columns are a mental model; memory is still one contiguous block.
In plain English
A 2D array is a grid of lockers. Rows and columns are labels, but the lockers still sit in one long row in memory.
Rows, columns, and row-major layout
int grid[3][4] has three rows and four columns. Elements are stored in row-major order, so the last index varies fastest. That means grid[0][0], grid[0][1], grid[0][2], and grid[0][3] are adjacent in memory before grid[1][0]. The first dimension is the number of rows; the second is the number of columns.
int grid[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};Nested traversal and function parameters
Nested loops are the natural way to traverse a 2-D array. The outer loop walks rows and the inner loop walks columns. When passing a 2-D array to a function, the column count must be part of the parameter type, because the compiler needs it to calculate row offsets.
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 4; c++) {
printf("%d ", grid[r][c]);
}
printf("\n");
}
void print_grid(int rows, int cols, int g[][4]);Key takeaways
- A 2-D array is an array of arrays.
- Elements are stored in row-major order.
- Nested loops traverse rows and columns.
- The column count is required in a function parameter type.
Common pitfalls
- Swapping row and column indexes.
- Assuming a 2-D array is stored column by column.
- Omitting the column count when passing it to a function.
Key focus
- Trace nested loops over 2-D arrays carefully.
- Know row-major order and the parameter syntax.
Quick check
1. In int a[3][4], how many elements does the array contain?
2. Which element is stored immediately after a[0][3] in row-major order?