开发者

Allocating memory to pointer structures inside structures

开发者 https://www.devze.com 2023-01-22 05:18 出处:网络
If I have a structure such as typedef struct _people { char *name; bool *exists; struct _p开发者_如何学编程eople **citizens;

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 */ }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消