Two-Dimensional Arrays
A 2D array is essentially an "array of arrays." It represents data in rows and columns, like a spreadsheet, a digital image, or a chess board.
Declaration
// data_type name[rows][columns];
int matrix[3][4]; // A grid with 3 rows and 4 columns (12 total items)
Initialization
int grid[2][3] = {
{1, 2, 3}, // Row 0
{4, 5, 6} // Row 1
};
Accessing Elements
You need two indices: one for the row and one for the column.
int val = grid[1][0]; // Accesses the 4 (Row 1, Column 0)
Visual Table Representation
| Col 0 | Col 1 | Col 2 | |
|---|---|---|---|
| Row 0 | [0][0] | [0][1] | [0][2] |
| Row 1 | [1][0] | [1][1] | [1][2] |
Processing with Nested Loops
To work with every item in a 2D array, you almost always use two nested for loops.
for (int i = 0; i < rows; i++) { // Outer loop for rows
for (int j = 0; j < columns; j++) { // Inner loop for columns
printf("%d ", matrix[i][j]);
}
printf("\n"); // Newline after each row
}
Memory Layout: Row-Major Order
In your computer's RAM, memory is a single long line. Even a 2D array is stored linearly: all of Row 0 first, followed by all of Row 1, and so on.
Multi-Dimensional Arrays
You aren't limited to 2D. You can have 3D (a cube), 4D, or more.
int cube[10][10][10]; // 1000 integers total
While possible, anything above 3D is extremely difficult for humans to visualize and is rarely used in standard business logic.
When passing a 2D array to a function, you must specify the number of columns in the function parameter: void process(int arr[][3]). The compiler needs this to calculate the memory offsets!