【问题标题】:allocating memory for structure via double pointer通过双指针为结构分配内存
【发布时间】:2026-02-21 22:15:01
【问题描述】:

您好,我在为属于第二个结构的结构分配内存时需要帮助,并且第二个结构具有双指针作为减速。

struct ant{ 
    int stu;
    int clas;
    char *name;
};

struct cat{
    int a;
    int b;
    struct ant *c;
};

int main()
{
   struct cat **sample;
   struct ant *info;

   info = calloc(1, sizeof(*info));

   <here i had allocated memory for **info** which is of type **ant**>
   <now i need to assig this **info** to the pointer which is there in **cat** structure>
   <how we can achive this> ?
}

【问题讨论】:

  • 你想和几只猫和蚂蚁一起玩?
  • 实际上是什么意思
  • 我怎么知道蚂蚁在初始化一只猫时应该如何分配内存?
  • 蚂蚁应该是一个

标签: c data-structures structure dynamic-memory-allocation


【解决方案1】:

您的cat 结构有一个成员c,它可以保存指向ant 结构的指针。 只需将指向 ant 结构的指针分配给 c 成员。 如果你有一个指向 cat 结构的双指针,你首先必须取消对它的引用。

struct cat *some_cat_p;
some_cat_p = calloc(1, sizeof(*some_cat_p));

struct cat **some_cat_pp;
some_cat_pp = &some_cat_p;

struct ant *some_ant_p;
some_ant_p = calloc(1, sizeof(*some_ant_p));


(*some_cat_pp)->c = some_ant_p; 

注意:你可能还想检查calloc和friends的返回值,如果分配内存失败,它可能会返回NULL

【讨论】:

  • 是的,我们可以这样做,但我需要 some_cat 应该是双指针
  • 结构猫 **some_cat
  • 编辑了答案
  • 是否不需要为 some_cat_pp 分配内存
  • 没有为 some_cat_pp 分配额外的内存