Thread: contiguous 3d array

  1. #1
    Registered User
    Join Date
    Nov 2009
    Posts
    24

    contiguous 3d array

    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; Z++)
    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

    The code I have been trying to use follows..I have tried swithcing these dimensions around here, but more or less always get the same results. When i do a print in a Z-X-Y loop it never comes out contiguous. This code also doesnt seem to work in all cases. I tried to make a 2-3-4 dimension matrix, and it was not working correctly

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

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    You cannot get guaranteed sequential memory by using pointer arrays.
    Code:
     
    char ***Arr3D;
    Any row to row sequentialism in memory you get from that will be coincidental.

    Code:
    Arr3d[X_DIM][Y_DIM][Z_DIM]
    Is guaranteed to be sequential.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. 3D Array of Bool
    By cybernike in forum C++ Programming
    Replies: 37
    Last Post: 06-28-2007, 11:17 AM
  3. 3D array
    By GSLR in forum C Programming
    Replies: 2
    Last Post: 05-12-2002, 04:00 PM
  4. 3D Array
    By Alextrons in forum Windows Programming
    Replies: 4
    Last Post: 01-11-2002, 01:39 AM
  5. Dynamic 3D array allocation
    By Vulcan in forum C++ Programming
    Replies: 4
    Last Post: 11-21-2001, 02:51 AM

Tags for this Thread