#include <stdio.h>
#include <stdlib.h>
typedef struct Map {
size_t xSize;
size_t ySize;
int mapData[];
} Map;
Map *allocate(size_t xSize, size_t ySize) {
// Allocate memory for the Map structure, including space for the 2D array data.
Map *map = malloc(sizeof(*map) + sizeof(map->mapData[0]) * xSize * ySize);
// Initialize map dimensions
if (map) {
map->xSize = xSize;
map->ySize = ySize;
}
return map;
}
// Macro to simplify accessing `mapData` as a 2D array.
#define ACCESS(map) ((int (*)[map->xSize])((map)->mapData))
int main(void)
{
// Allocate a map with dimensions 10x20.
Map *mp = allocate(10, 20);
// Use the ACCESS macro to access and set an element in the mapData.
ACCESS(mp)[3][5] = 2347;
printf("%d\n", ACCESS(mp)[3][5]);
free(mp);
}
/*
run:
2347
*/