Reputation: 1621
Suppose we have an array a[90][30][40] where first element starts from a[1][1][1] then what will be the index of a[20][20][30] in column major representation ?
According to me a[x][y][z] means x is depth, y is rows and z is columns.
So according to me, the index should be 19(30)(40) + (29)(30) + (20-1) = 23689.
I read https://eli.thegreenplace.net/2015/memory-layout-of-multi-dimensional-arrays/ which says that a[x][y][z] actually means x is rows, y is columns and z is depth.
I read all the existing answers here and also the above link and got confused.
Is my calculation correct?
Upvotes: 1
Views: 1206
Reputation: 67476
I have asked you in the comment what have you done to sort this puzzle out? Not your "calculations". It is enough to write three lines of the code to get the answer:
char a[10][10][10];
for (int i = 0; i < 10; i++)
printf("&a[%1d][0][0] = %04zu\t\t&a[0][%1d][0] = %04zu\t\t&a[0][0][%1d] = %04zu\n", i, &a[i][0][0] - &a[0][0][0], i, &a[0][i][0] - &a[0][0][0], i, &a[0][0][i] - &a[0][0][0]);
&a[0][0][0] = 0000 &a[0][0][0] = 0000 &a[0][0][0] = 0000
&a[1][0][0] = 0100 &a[0][1][0] = 0010 &a[0][0][1] = 0001
&a[2][0][0] = 0200 &a[0][2][0] = 0020 &a[0][0][2] = 0002
&a[3][0][0] = 0300 &a[0][3][0] = 0030 &a[0][0][3] = 0003
&a[4][0][0] = 0400 &a[0][4][0] = 0040 &a[0][0][4] = 0004
&a[5][0][0] = 0500 &a[0][5][0] = 0050 &a[0][0][5] = 0005
&a[6][0][0] = 0600 &a[0][6][0] = 0060 &a[0][0][6] = 0006
&a[7][0][0] = 0700 &a[0][7][0] = 0070 &a[0][0][7] = 0007
&a[8][0][0] = 0800 &a[0][8][0] = 0080 &a[0][0][8] = 0008
&a[9][0][0] = 0900 &a[0][9][0] = 0090 &a[0][0][9] = 0009
Upvotes: 1
Reputation: 73366
Is my calculation correct?
No, since your basis is wrong.
The first element is a[0][0][0]
, since indexing starts from 0 in arrays, not 1.
Usually, the first dimension of a 3D array is the rows, the second the columns, and the third the depth.
There are two popular representation when it comes to arrays, row and column major order.
It seems like you are confused and talk about Fortran arrays (where the arrays are column major ordered, and the index starts from 1), rather than C ones.
Upvotes: 1