Malloc of arrays and structs within a struct

后端 未结 5 1124
无人共我
无人共我 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 12:58

    A struct included inside another struct is contained by copy, so you would not have to separately malloc it. If the struct contains a pointer to another struct, then you can consider allocating memory for it dynamically.

    struct Point2d
    {
        float x;
        float y;
    };
    
    struct Rect
    {
        struct Point2D a;
        struct Point2D b;
    };
    
    struct LinkedListNode
    {
        struct LinkedListNode* next;
        int value;
    };
    

    In struct Rect, the struct Point2D element are inserted into struct Rect and you don't have to dynamically allocate memory for them. On the contrary in the struct LinkedListNode the next element is referenced by a pointer and the memory must be dynamically allocated.

    The two version are both useful, depending on the situation. There is no correct way to manage memory, it'll depend on your usage.

    This same situation occurs in the case of an array. If your array is statically sized, then it can be directly included in the struct. However, if the size can vary, you must store a pointer within the struct.

    struct Header
    {
        char magic[4];
        unsigned int width;
        unsigned int height;
    };
    
    struct Buffer
    {
        char* data;
        unsigned int size;
        unsigned int capacity;
    };
    
    struct Buffer* buffer_init()
    {
        struct Buffer* buffer = (struct Buffer*)malloc(sizeof(struct Buffer));
        buffer->data = 0;
        buffer->size = 0;
        buffer->capacity = 0;
    }
    
    void buffer_grow(struct Buffer* buffer, size_t capacity)
    {
        if (capacity > buffer->capacity)
        {
            buffer->data = realloc(buffer->data, capacity);
            buffer->capacity = capacity;
        }
    }
    
    void buffer_append(struct Buffer* buffer, const char* data, unsigned int dataLen)
    {
        if (dataLen + buffer->size > buffer->capacity)
            buffer_grow(MAX(dataLen + buffer->size, buffer->capacity * 2));
    
        memcpy(buffer->data + buffer->size, data, dataLen);
        buffer->size += dataLen;
    }
    

    The realloc function only does a shallow copy, that is pointer value is copied, but not the pointed object. One more time, how you deal with it will depend on your application.

提交回复
热议问题