好的,对于我正在研究的视频游戏的结构,我需要在结构“dungeon”中分配“房间”结构。不幸的是,我似乎无法分配足够的内存来提供我需要的所有信息。以下是我的数据结构示例:
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;
这就是我收到分段错误的地方。
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;
为什么我会遇到seg-fault?我分配了足够的内存吗?
答案 0 :(得分:1)
您没有为room[0].sentry
分配内存。尝试:
room[0].sentry = malloc(sizeof *room[0].sentry);
*room[0].sentry = ...
或者,您可以只指定指针(我想如果在您的情况下效果更好):
room[0].sentry = &room[1];