How can I malloc a struct array inside a function? Code works otherwise

Function arguments are passed by value in C and modifying arguments in callee won’t affect caller’s local variables.

Use pointers to modify caller’s local variables.

void CreateMap(MapTileData ***Map, int xSize, int ySize)
{
    //Variables
    int i;

    //Allocate Initial Space
    *Map = calloc(xSize, sizeof(MapTileData));

    for(i = 0; i < xSize; i++)
    {
        (*Map)[i] = calloc(ySize, sizeof(MapTileData));
    }
}

Usage in the code:

MapTileData **MapTile;

CreateMap(&MapTile,5,5);

Alternate way: Pass the allocated array via the return value.

MapTileData **CreateMap(int xSize, int ySize)
{
    //Variables
    MapTileData **Map;
    int i;

    //Allocate Initial Space
    Map = calloc(xSize, sizeof(MapTileData));

    for(i = 0; i < xSize; i++)
    {
        Map[i] = calloc(ySize, sizeof(MapTileData));
    }

    //Return the value
    return Map;
}

Usage in the code:

MapTileData **MapTile;

Maptile = CreateMap(5,5);

Also note that they say you shouldn’t cast the result of malloc() and its family in C.

Leave a Comment