Malloc of arrays and structs within a struct

后端 未结 5 1135
无人共我
无人共我 2021-02-14 12:09

How does one malloc a struct which is inside another struct?

I would also like to malloc an array of items inside a struct and then realloc this array when needed, how i

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-14 12:55

    typedef struct _A
    {
      int *arr;
      int arrCount;
    } A;
    
    void Construct_A(A *a, int arraySize)
    {
      a->arrCount = arraySize;
      a->arr = (int*)malloc(sizeof(int)*arraySize);
    }
    
    void Destruct_A(A *a)
    {
      free(a->arr);
      a->arr = 0;
    }
    
    typedef struct _B
    {
      A *a;
    } B;
    
    void Construct_B(B *b, int arraySize_A)
    {
      b->a = (A*)malloc(sizeof(A));
      Construct_A(b->a);
    }
    
    void Destruct_B(B *b)
    {
      Destruct_A(b->a);
      free(b->a);
      b->a = 0;
    }
    
    void main()
    {
      B b;
      Construct_B(&b, 10);
    
      // Use b and b->a
    
      Destruct_B(&b);
    }
    

提交回复
热议问题