2010-10-26 122 views
1

指針結構如果我有作爲分配內存內部結構

typedef struct _people { 
char *name; 

bool *exists; 

struct _people **citizens; 
} PEOPLE; 

我怎麼去,這樣以人爲>公民[0]分配內存這樣的結構 - >名稱進行訪問?我試過

info->citizens = malloc(sizeof(PEOPLE *)*numbPeople); 

然而,當我嘗試訪問信息 - > citizens->名字我得到了GDB的錯誤消息:

Program received signal EXC_BAD_ACCESS, Could not access memory. 
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000008 

回答

4

(我不喜歡typedefing結構中下沒有理由)

讓sizeof爲您完成工作。

info->citizens = malloc(numbPeople * sizeof *info->citizens) 
if (!info->citizens) { /* could not malloc - do something */ } 

int i; 
for (i = 0; i < numbPeople; ++i) { 
    info->citizens[i] = malloc(sizeof *info->citizens[i]); 
    if (!info->citizens[i]) { /* could not malloc - do something */ } 
}