In C, I want to loop through an array in this order
for(int z = 0; z < NZ; z++)
for(int x = 0; x < NX; x++)
for(int y = 0; y < NY; y++)
3Darray[x][y][z] = 100;
How do I create this array in such a way that 3Darray[0][1][0] comes right before 3Darray[0][2][0] in memory?
I can get an initialization to work that gives me “z-major” ordering, but I really want a y-major ordering for this 3d array
This is the code I have been trying to use:
char *space;
char ***Arr3D;
int y, z;
ptrdiff_t diff;
space = malloc(X_DIM * Y_DIM * Z_DIM * sizeof(char))
Arr3D = malloc(Z_DIM * sizeof(char **));
for (z = 0; z < Z_DIM; z++)
{
Arr3D[z] = malloc(Y_DIM * sizeof(char *));
for (y = 0; y < Y_DIM; y++)
{
Arr3D[z][y] = space + (z*(X_DIM * Y_DIM) + y*X_DIM);
}
}
I think the only way to do this is to write your own wind/unwind functionality on a contiguous datastore. In other words you are going to have to write your own map to calculate the storage position of your values.
If you are trying to make a certain order traversal of your array more efficient, you could always transform the incoming matrix before you put it into the array and then do the transform again when you get it out. C style multi-dimensional arrays are packed order, so the math might get a bit tricky (and is beyond what I can detail out here in the time I have).
Sorry for not having a better answer, but I hope that helps