C Multi-dimensional Arrays
In this page:
Two-Dimensional Arrays
Internally, a 2D array is still stored as one contiguous block of memory in row-major order, meaning an entire row is stored before the next row begins -- this layout is why looping row-by-row is more cache-friendly than column-by-column.
Example: Two-Dimensional Arrays
#include <stdio.h>
int main() {
int grid[2][2] = {{1, 2}, {3, 4}};
printf("%d", grid[1][0]);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Initializing 2D Arrays
When you initialize with nested braces like {{1,2},{3,4}}, each inner group fills one row in order; if you provide fewer values than a row needs, the remaining elements in that row are automatically set to zero.
Example: Initializing 2D Arrays
#include <stdio.h>
int main() {
int grid[2][2] = {{1, 2}, {3}};
printf("%d", grid[1][1]);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Accessing Elements in 2D Arrays
grid[2][3] reads as 'row 2, column 3' -- mixing up the order is a frequent source of bugs, especially when translating between mathematical matrix notation (which some fields write row-first, others column-first) and code.
Example: Accessing Elements in 2D Arrays
#include <stdio.h>
int main() {
int grid[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
printf("%d", grid[2][3]);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Modifying Elements in 2D Arrays
Just like 1D arrays, updating grid[i][j] only changes that single cell; there's no built-in way to reassign an entire row at once except by looping or using memcpy() on that row's contiguous memory.
Example: Modifying Elements in 2D Arrays
#include <stdio.h>
int main() {
int grid[2][2] = {{1, 2}, {3, 4}};
grid[0][1] = 99;
printf("%d", grid[0][1]);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Looping Through 2D Arrays
The outer loop variable typically represents the row and the inner loop the column (or vice versa, as long as you're consistent) -- getting the loop bounds wrong for either dimension is easy to do and will either skip data or read out of bounds.
Example: Looping Through 2D Arrays
#include <stdio.h>
int main() {
int grid[2][2] = {{1, 2}, {3, 4}};
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 2; col++) {
printf("%d ", grid[row][col]);
}
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: