If I have a structure such as
typedef struct _people {
char *name;
bool *exists;
struct _p开发者_如何学编程eople **citizens;
} PEOPLE;
How do I go about allocating memory so that people->citizens[0]->name is accessible? I've tried
info->citizens = malloc(sizeof(PEOPLE *)*numbPeople);
However when I try to access info->citizens->name I get the error message in GDB:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000008
(I dislike typedefing structs in C for no reason)
Let sizeof do the work for you.
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 */ }
}
精彩评论