I want to allocate memory for a data cube in C language. I mean, I need to allocate a 3D array. My code, however, returns a segmentation fault and I don't know why.
I believe my loops are right, but the fact is, my code doesn't work.
This is my code:
int malloc3dfloat(float ****array, int q, int r, int s) {
// allocate the q*r*s contiguous items
float *p = (float *) malloc(q*r*s*sizeof(float));
if (!p) return -1;
// allocate the row pointers into the memory
(*array) = (float ***) malloc(q*sizeof(float**));
if (!(*array)) {
free(p);
return -1;
}
for (int i=0; i<q; i++)
{
(*array)[i] = (float **) malloc(r*sizeof(float*));
if (!(*array[i]))
{
free(p);
return -1;
}
}
//set up the pointers into the contiguous memory
for (int i=0; i<q; i++)
{
for (int j=0; j<r; j++)
{
(*array)[i][j] = &(p[(i*r+j)*s]);
}
}
return 0;
}