Malloc of arrays and structs within a struct

后端 未结 5 1145
无人共我
无人共我 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条回答
  •  無奈伤痛
    2021-02-14 13:00

    It's not very readable but sometimes people create a structure with a count member and a final single-element array member. There then is a special factory method that allocates enough space so that you can write to count elements in the array. Obviously the array member can be of any type.

    typedef struct {
        int count;
        int elements[1];
    } int_array;
    
    int_array* allocate_int_array(int count)
    {
        int_array* mem = (int_array*)malloc(sizeof(int_array) + (count - 1) * sizeof(int));
        if (mem)
            mem->count = count;
        return mem;
    }
    

提交回复
热议问题