c / intermediate
Snippet
Row-Major Storage in Multi-dimensional Arrays
In C, multi-dimensional arrays are stored in 'row-major' order, meaning elements of the first row are placed consecutively in memory, followed by the second row. Accessing them linearly proves they occupy a single contiguous block of memory.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>int main() {int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};int *flat = (int *)matrix;for (int i = 0; i < 6; i++) {printf("%d ", flat[i]);}return 0;}
Breakdown
1
int matrix[2][3]
Declares a 2D array with 2 rows and 3 columns.
2
int *flat = (int *)matrix;
Casts the 2D array to a pointer to demonstrate its contiguous nature.