[英]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
. 您没有为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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.