PSkocik PSkocik - 1 month ago 5
C Question

Casting a flat pointer to a multidimensional array

Is it possible to get the compiler to do the same pointer arithmetic on flat pointers as it does on multidimensional arrays?

With multidimensional arrays, the pointer arithmetic appears to work as follows:

int main(void)
{
char ar[2][3][4];
#define At(a,x,y,z) printf("["#x"]["#y"]["#z"]=%ld\n", &(a)[x][y][z] - &(a)[0][0][0]);
At(ar,0,0,0);
At(ar,0,0,1);
At(ar,0,0,2);
At(ar,0,0,3);
puts("");
At(ar,0,1,0);
At(ar,0,2,0);
At(ar,0,3,0);
puts("");
At(ar,1,0,0);
At(ar,2,0,0);
At(ar,3,0,0);
/*
[0][0][0]=0
[0][0][1]=1
[0][0][2]=2
[0][0][3]=3

[0][1][0]=4 // 1 * 4
[0][2][0]=8 // 2 * 4
[0][3][0]=12 // 3 * 4

[1][0][0]=12 // 1 * 3 * 4
[2][0][0]=24 // 2 * 3 * 4
[3][0][0]=36 // 3 * 3 * 4
*/
}


So I tried:

char blk[1000];
char (*p)[2][3][4] = (char(*)[2][3][4])&blk;

At(p,0,0,0);
At(p,0,0,1);
At(p,0,0,2);
At(p,0,0,3);
puts("");
At(p,0,1,0);
At(p,0,2,0);
At(p,0,3,0);
puts("");
At(p,1,0,0);
At(p,2,0,0);
At(p,3,0,0);

/*
[0][0][0]=0
[0][0][1]=1
[0][0][2]=2
[0][0][3]=3

[0][1][0]=3
[0][2][0]=6
[0][3][0]=9

[1][0][0]=6
[2][0][0]=12
[3][0][0]=18
*/
}


But as you can see, this doesn't give corresponding results.
What exactly is going on here? Can the results be made to match?

Answer

I think you are missing a dereference. You now have a pointer to a 3 dimensional array.

You need to do this:

At(*p, 0, 0, 1);
Comments