Search code examples
carrayslow-level

How are 3D arrays stored in C?


I understand that arrays in C are allocated in row-major order. Therefore, for a 2 x 3 array:

0  1
2  3
4  5

Is stored in memory as

0 1 2 3 4 5

However, what if I have a 2 x 3 x 2 array:

0  1
2  3
4  5

and

6  7
8  9
10 11

How are these stored in memory? Is just consecutive like:

0 1 2 3 4 5 6 7 8 9 10 11

Or is it some other way? Or does it depend on something?


Solution

  • 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