简体   繁体   中英

allocating memory for structure via double pointer

HI I need help in allocating memory for a structure which is part of 2nd structure and 2nd structure is having double pointer as deceleration.

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

Your cat struct has a member c that can hold a pointer to an ant struct. Just assign the pointer to your ant struct to the c member. If you have a double pointer to a cat struct, you first have to dereference it.

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; 

Note: You may also want to check the return value of calloc and friends, it may return NULL if it fails to allocate memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM