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