Dynamically allocate Large 4-D arrays
Hello,
For a project I am working on, I need to be able to dynamically allocate large 4-dimensional arrays. The code I am using to do this is:
Code:
void allocate_data_mem(size_t count0, size_t count1, size_t count2, size_t count3, double *****data)
{
int i, j, k, l;
*data = (double ****)malloc(count2*sizeof((*data)));
if ((*data) != NULL) {
for(i = 0; i < count2; i++) {
(*data)[i] = (double ***)malloc(count3*sizeof((*data)));
if ((*data)[i] != NULL) {
for(j = 0; j < count3; j++) {
(*data)[i][j] = (double **)malloc(count1*sizeof((*data)));
if ((*data)[i][j] != NULL) {
for (k = 0; k < count1; k++) {
(*data)[i][j][k] = (double *)malloc(count0*sizeof((*data)));
if ((*data)[i][j][k] == NULL) {
printf("Mem allocation failed\n");
exit(1);
}
}
}
else {
printf("Mem allocation failed\n");
exit(1);
}
}
}
else {
printf("Mem allocation failed\n");
exit(1);
}
}
}
else {
printf("Mem allocation failed\n");
exit(1);
}
}
It works fine, but the problem is it is slow. For a 300x400x30x10 array, this code will use 3.6 million malloc calls and takes about 0.5 seconds to complete. The program as a whole will do this many times, so the time adds up.
Is there another way to accomplish this using fewer mallocs?
Thanks.