How do you dynamically allocate a contiguous 3D array in C?

Posted by Derek on Stack Overflow See other posts from Stack Overflow or by Derek
Published on 2010-03-09T19:46:05Z Indexed on 2010/04/09 3:53 UTC
Read the original article Hit count: 424

Filed under:
|
|
|

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);
    }
}

© Stack Overflow or respective owner

Related posts about 3d

Related posts about array