I'm trying to refactor my code to make it better/more readable so I'm trying change a 2-D variable array allocation as follows
// OLD CODE
int **map;
map = calloc(number, sizeof(int *));
if (!(map)) {
free(map);
return 1;
}
for (int i = 0; i < number; i++) {
map[i] = calloc(number, sizeof(int));
if (!(map[i])) {
while (--i >= 0) {
free(map[i]);
}
free(map);
return 1;
}
}
// NEW CODE
int (*map)[number] = malloc(sizeof (int[number][number]));
if (!(map)){
free(map);
return 1;
}
The problem is that all my functions that use map take int **map
and by changing the declaration of map like i did the IDE tells me incorrect type int[]* instead of int**
What should i use instead of int**
? Using int[]* map
in the function declaration tells me can't resolve variable map
To use one allocation with standard code, unlike the other answer, is a bit trickier as one needs to insure that a combined memory allocation of pointers and
int
needs to meet alignment concerns in the unusual case ofint
alignment requirements exceed pointer alignment ones. This is more easily shown withlong long
as below.If this makes "code easier to read" is left to OP's judgment.
Sample output
Turns out the below code is not a C99 alternative @M.M, but a GCC extension.
Undocumented GCC Extension: VLA in struct
As a
C99GCC extension alternative toint (*map)[number] = malloc(sizeof (int[number][number]));
for code simplification and maintain compatibility with existing function set, allocate all the memory needed with 1*alloc()
call.This does require that when code is done with the
map
, all the memory is free'd with onefree(map)
. Further, individual rows ofmap[]
can no longer be re-allocated, but can be swapped within themap[]
.Note: no casting and field
i[][]
is properly aligned.