【问题标题】:Allocating memory to pointer structures inside structures将内存分配给结构内的指针结构
【发布时间】:2010-10-26 11:47:48
【问题描述】:

如果我有这样的结构

typedef struct _people {
 char *name;

 bool *exists;

 struct _people **citizens;
} PEOPLE;

如何分配内存以便 people->citizens[0]->name 可访问?我试过了

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 memory gcc gdb allocation


    【解决方案1】:

    (我无缘无故不喜欢 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 */ }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2017-01-03
      • 1970-01-01
      • 2019-09-23
      • 2021-11-26
      • 1970-01-01
      相关资源
      最近更新 更多