Turns out the below code is not a C99 alternative @M.M, but a GCC extension.
Undocumented GCC Extension: VLA in struct
As a C99 GCC extension alternative to int (*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 one free(map)
. Further, individual rows of map[]
can no longer be re-allocated, but can be swapped within the map[]
.
int **map_allocate(size_t row, size_t column) {
struct {
int *ip[row]; // Array of pointers, followed by a ...
int i[row][column]; // 2D array of int
} *u;
u = calloc(1, sizeof *u);
if (u == NULL) {
return NULL;
}
for (size_t i = 0; i<row; i++) {
u->ip[i] = u->i[row];
}
return &u->ip[0];
}
Note: no casting and field i[][]
is properly aligned.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…