2

How is a three dimensional array stored in memory?

For example, a two dimensional array is stored in terms of rows and columns d[rows][columns]; in the case of three a dimensional array d[?][?][?] how are the elements arranged in c?

pat
  • 12,587
  • 1
  • 23
  • 52
Karthikeyan
  • 381
  • 8
  • 19
  • 1
    possible duplicate of [How are multi-dimensional arrays formatted in memory?](http://stackoverflow.com/questions/2565039/how-are-multi-dimensional-arrays-formatted-in-memory) – Lee Duhem Mar 01 '14 at 05:52

2 Answers2

2

Possible duplicate: How are multi-dimensional arrays formatted in memory?

Multidimensional arrays are laid out contiguously in memory, not as rows and columns.

For eg. If you have

Array[5][2]={{0,1},{2,3},{4,5},{6,7},{8,9}};

It'll be stored in memory as:

| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |

and not as:

| 0 | 1 | 
| 2 | 3 | 
| 4 | 5 | 
| 6 | 7 | 
| 8 | 9 |

And a 3D array is essentially an array of 2D arrays: ie

Array[2][5][2]= Array_1[5][2], Array_2[5][2]

If

Array_1[5][2]={{0,1},{2,3},{4,5},{6,7},{8,9}};

and

Array_2[5][2]={{10,11},{12,13},{14,15},{16,17},{18,19}};

So, in memory this 3D array will be laid out as:

| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 |
Community
  • 1
  • 1
brokenfoot
  • 11,083
  • 10
  • 59
  • 80
0

C uses row-major layout. When 2D array (i.e. matrix) is linearized, the first row is stored first, then the second row, the third row then follows and so on. Similarly for N-dimensional arrays.

Petr Vepřek
  • 1,547
  • 2
  • 24
  • 35