I'm translating some MATLAB code into C and the script I'm converting makes heavy use of 3D arrays with 10*100*300 complex entries. The size of the array also depends on the sensor's input, ideally the array should be allocated dynamically. So far I've tried two approaches the first being a flat 1D array along the lines of
value = array[x + (y*xSize) + (z*ySize*xSize)]
Which hurts my brain to use. I've also tried an array of an array of pointers
int main () { int ***array = malloc(3*sizeof(int**)); int i, j; for (i = 0; i < 3; i++) { *array[i] = malloc(3*sizeof(int*)); for (j = 0; j < 3; j++) { array[i][j] = malloc(3*sizeof(int)); } } array[1][2][1] = 10; return 0; }
Which gives a seg fault when I try to assign data.
In a perfect world, I'd like to use the second method with the array notation for cleaner, easier programming. Is there a better way to dynamically allocate a three-dimensional array in C?
In c programming, the array is used to store a range of values of the same data type and it occupies some space in memory which can be either static or dynamic. The malloc is a function used in the c programming for dynamic memory allocation.
A 2D array can be dynamically allocated in C using a single pointer. This means that a memory block of size row*column*dataTypeSize is allocated using malloc and pointer arithmetic can be used to access the matrix elements.
Because in physical memory, arrays are stored by column, such that all of column 1's contents reside consecutively then column 2's, column 3's, and so on. Such arrangement in memory is known as column major order. Not all programming languages will be column major order, some will be row major order.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With