Dynamically Allocating a Struct within a Struct

后端 未结 3 2049
迷失自我
迷失自我 2021-02-09 21:08

I am dynamically allocating a struct which has a different struct as a member:

struct a {
   // other members
   struct b;
}

struct b

3条回答
  •  一个人的身影
    2021-02-09 21:50

    If you dynamically allocate (malloc) struct a as in

    struct a *temp = (struct a *)malloc(sizeof(struct a));
    

    you malloc space for a pointer to struct b (assuming that's what is in struct a) but you don't malloc space for struct b. That means later you'll have to do

    temp->b = (struct b *)malloc(sizeof(struct b));
    

    before you try and use struct b.

    If you don't store a pointer to struct b but rather struct b directly then you'll get the automatic allocation when you define struct a.

提交回复
热议问题