Malloc a 3-Dimensional array in C?

I’d go for the first option (the single 1D array) as it will give you a single block of memory to play in rather than potentially thousands of fragmented memory blocks

If accessing the correct element of the array is doing your head in though, I’d write a utility method to convert x, y, z locations into an offset into the 1D array

int offset(int x, int y, int z) { 
    return (z * xSize * ySize) + (y * xSize) + x; 
}

Leave a Comment