2012-03-05 66 views
0

好的,對於我正在研究的視頻遊戲的結構,我需要在結構「地下城」內分配結構「房間」。不幸的是,我似乎無法分配足夠的內存來存放我需要的所有信息。這裏是我的數據結構的示例:Segfault。爲結構體內的struct分配內存

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?我是否分配了足夠的內存?

回答

1

您沒有爲room[0].sentry分配內存。嘗試:

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

或者,你可以只分配指針(我想,如果會更好地工作,你的情況):

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

謝謝!這幫助了很多。有一個問題,通過分配一個指針,我仍然可以爲所有單獨的房間分配足夠的內存嗎? – atb 2012-03-05 20:01:01

+0

@alexthebake通過分配指針'room [0] .sentry'和'room [1]'指向相同的東西。所以如果你改變一個,如果會反映到另一個。 – cnicutar 2012-03-05 20:03:18