How are 3D arrays stored in C?
At a low level, there is no such thing as a multi-dimensional array. There is just a flat block of memory, large enough to hold a given number of elements. In C, a multi-dimensional array is conceptually an array whose elements are also arrays. So if you do:
int array[2][3];
Conceptually you end up with:
array[0] => [0, 1, 2]array[1] => [0, 1, 2]
This results in the elements being arranged contiguously in memory, because array[0]
and array[1]
are not actually holding any data, they are just references to the two inner arrays. Note that this means that only the [0, 1, 2]
entries actually occupy space in memory. If you extend this pattern out to the next dimension, you can see that:
int array[2][3][2];
...will give you a structure like:
array[0] => [0] => [0, 1] [1] => [0, 1] [2] => [0, 1]array[1] => [0] => [0, 1] [1] => [0, 1] [2] => [0, 1]
Which continues arranging the elements consecutively in memory (as above, only the [0, 1]
entries actually occupy space in memory, everything else is just part of a reference to one of these entries). As you can see, this pattern will continue no matter how many dimensions you have.
And just for fun:
int array[2][3][2][5];
Gives you:
array[0] => [0] => [0] => [0, 1, 2, 3, 4] [1] => [0, 1, 2, 3, 4] [1] => [0] => [0, 1, 2, 3, 4] [1] => [0, 1, 2, 3, 4] [2] => [0] => [0, 1, 2, 3, 4] [1] => [0, 1, 2, 3, 4]array[1] => [0] => [0] => [0, 1, 2, 3, 4] [1] => [0, 1, 2, 3, 4] [1] => [0] => [0, 1, 2, 3, 4] [1] => [0, 1, 2, 3, 4] [2] => [0] => [0, 1, 2, 3, 4] [1] => [0, 1, 2, 3, 4]
All "dimensions" are stored consecutively in memory.
Consider
int arr[4][100][20];
you can say that arr[1]
and arr[2]
(of type int[100][20]
) are contiguous
or that arr[1][42]
and arr[1][43]
(of type int[20]
) are contiguous
or that arr[1][42][7]
and arr[1][42][8]
(of type int
) are contiguous
Yep, you're right - they are stored consecutively. Consider this example:
#include <stdio.h>int array3d[2][3][2] = { {{0, 1}, {2, 3}, {3, 4}}, {{5, 6}, {7, 8}, {9, 10}}};int main(){ int i; for(i = 0; i < 12; i++) { printf("%d ", *((int*)array3d + i)); } printf("\n"); return 0;}
Output:
0 1 2 3 3 4 5 6 7 8 9 10