简体   繁体   中英

How to free a 2d array of structs in c99

This is how I create the 2d array.

   Space **create_map( int row, int col) {
        Space **map = malloc(row * sizeof(Space*));
        for (int i = 0; i < row; ++i)
            map[i] = malloc(sizeof(Space) * col);
        return map;
    }

This is the components of the struct

typedef struct Space{
    char character;
    int isVisited;
    int row;
    int column;
    int stepCount;
}Space;

How would I free this?

You need to free the memory in "reverse" from when you allocated it. So firstly, you need to free the elements of the array (or other struct), and then free the pointer.

void freeMap(Space map){
    for (int i = 0; i < row; ++i)
        free(map[i]);
    free(map);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM