简体   繁体   中英

Segfault. Allocating memory for struct within a struct

Okay, so for the structure of a video game I'm working on, I need to allocate the structure "rooms" inside the structure "dungeon." Unfortunately I can't seem to allocate enough memory to put all the information I need. Here is a sample of my data structure:

typedef struct monster {
    int difficulty;
    char *name;
    char *type;
    int hp;
} monster;

typedef struct rooms {
    int n_monsters;
    int visited;
    struct rooms *nentry;
    struct rooms *sentry;
    struct rooms *wentry;
    struct rooms *eentry;
    monster *monsters;
} rooms;

typedef struct dungeon {
    char *name;
    int n_rooms;
    rooms *rm; // Subject to change
    rooms sroom;
} dungeon;

And this is where I'm getting my Segmentation Fault.

d->name = "Dungeon 1";
d->n_rooms = 10;
rooms *room = malloc(d->n_rooms * sizeof(rooms));

// Room 0
room[0].n_monsters = 1;
room[0].visited = 0;
*room[0].sentry = room[1]; // xCode is showing the seg-fault here

// Room 2
room[1].n_monsters = 1;
room[1].visited = 0;
*room[1].nentry = room[0];

d->rm = room;

Why am I getting a seg-fault? Am I allocating enough memory?

You didn't allocate memory for room[0].sentry . Try:

room[0].sentry = malloc(sizeof *room[0].sentry);
*room[0].sentry = ...

Alternatively, you could just assign the pointer (I think if would work better in your case):

room[0].sentry = &room[1];

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