首页 > 解决方案 > 通过双指针为结构分配内存

问题描述

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

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> ?
}

标签: cdata-structuresstructuredynamic-memory-allocation

解决方案


您的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 和朋友的返回值,NULL如果分配内存失败,它可能会返回。


推荐阅读