Hello.
I have been reading this forum for quite some time, and this is my first post.
I often have the need to dynamically allocate memory for arrays with multiple dimensions. In my opinion I find it quite ugly to litter the code with multiple for-loops and mallocs every time I need one.
I have created this macro to allocate memory for a three-dimensional array, regardless of type:
#define allocate_cube(type, var, x, y, z) \
do { \
(var) = malloc(sizeof(type **) * (x)); \
if ((var) == NULL) { \
perror("Error allocating memory.\n"); \
} \
int i, j; \
for (i = 0; i < x; i++) { \
(var)[i] = malloc(sizeof(type*) * (y)); \
if ((var)[i] == NULL) { \
perror("Error allocating memory.\n"); \
} \
for (j = 0; j < y; j++) { \
(var)[i][j] = malloc(sizeof(type) * (z)); \
if ((var)[i][j] == NULL) { \
perror("Error allocating memory.\n"); \
} \
} \
} \
} while(0)
The macro is used in the following way:
int ***array;
array = allocate_cube(int, array, 5, 10, 15);
Is this considered bad practice? I have used functions to do this before, but it makes it almost impossible to track the origin of the memory allocation, when debugging.
Any thoughts or comments are appreciated :)