Dynamically Allocating a Struct within a Struct

后端 未结 3 2039
迷失自我
迷失自我 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

    First, let's get some real definitions in place to make this concrete.

    struct b {
        int x;
    };
    
    struct a_with_b {
        struct b b;
    }
    
    struct a_with_b_ptr {
        struct b *bp;
    }
    

    When you encapsulate a struct, you just need to allocate the outer struct (and since the inner struct is not a pointer, you use . to reference members of the innert struct):

    struct a_with_b *a1 = malloc(sizeof(struct a_with_b));
    a1->b.x = 3;
    

    But when you encapsulate a pointer, you have to allocate each independently and use -> when referencing members of the inner struct:

    struct a_with_b_ptr *a2 = malloc(sizeof(struct a_with_b_ptr));
    a1->b = malloc(sizeof(struct b));
    a1->b->x = 3;
    

提交回复
热议问题