C Multidimensional Arrays
A multidimensional array stores data in more than one dimension, like a table of rows and columns. The most common form is a two-dimensional array, declared with two sizes in square brackets.
Multidimensional arrays are useful for representing grids, matrices, images, and other tabular data structures.
type name[rows][cols] = {{...}, {...}};Declaring 2D arrays
A 2D array is declared as `int grid[rows][cols];`. Internally, it's stored as contiguous memory in row-major order, meaning each row's elements are stored one after another.
Accessing elements
An element is accessed using two indexes, like `grid[1][2]` for the row-1, column-2 element. Nested for loops are the standard way to visit every element.
#include <stdio.h>
int main() {
int grid[2][2] = {{1, 2}, {3, 4}};
printf("%d\n", grid[1][0]);
return 0;
}3grid[1][0] accesses row index 1, column index 0, which holds 3.
#include <stdio.h>
int main() {
int grid[2][2] = {{1, 2}, {3, 4}};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", grid[i][j]);
}
}
printf("\n");
return 0;
}1 2 3 4 Nested loops visit every row and column of the 2D array in order.
Key points
- 2D arrays are declared with two sizes: rows and columns.
- Elements are accessed with two indexes, e.g. grid[row][col].
- C stores 2D arrays in row-major order in memory.
- Nested loops are the standard way to process every element.
