I have a array of somestruct_t I’m adding to but don’t know in advance how many elements it will need. So I malloc 5 slots of space to start with but I need to encapsulate it in another struct that saves the array boundary and whats used so far so I don’t overflow. I’ll realloc if it looks like it will overflow.
typedef struct {
somestruct_t[] *data;
uint32_t max_size;
uint32_t used;
} something_box_t;
Is this the idiomatic way to do this?
One thing that’s done in C sometimes is to use a zero length array at the end of a struct and to allocate extra space for a variable number of elements. I’m not sure if zero length arrays are legal in C (they’re not in C++) but it’s commonly supported.
Of course, if you can switch to C++ you won’t have to hack together a solution on your own. You could just do
std::vector<somestruct_t> box;and have a solution far easier to use, as performant if not more performant, and more reliable than what you’re likely to write in C.