如果我有
这样的结构typedef struct _people {
char *name;
bool *exists;
struct _people **citizens;
} PEOPLE;
如何分配内存以便人们可以访问人员> citizen [0] - >名称?我试过了
info->citizens = malloc(sizeof(PEOPLE *)*numbPeople);
但是当我尝试访问info-> citizen-> name时,我在GDB中收到错误消息:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000008
答案 0 :(得分:4)
(我不喜欢C中的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 */ }
}