views:

45

answers:

1

If I have a structure such as

typedef struct _people {
 char *name;

 bool *exists;

 struct _people **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
+2  A: 

(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 */ }
}
eq-