Search code examples
cmallocrealloc

c, malloc and realloc an array of structs


Let's say I have a struct called Thing. If I want to have an array of "Thing", yet it doesn't have a fixed size (dynamic), how do I go about allocating space for it? Do I initially malloc space for the array itself, and then have to realloc space every time I add an element to it? For example:

struct Thing{
    char *stuff;
    char **morestuff;
    int evenmorestuff;
};

Thing *thingarray;
thingarray = malloc(sizeof(Thing));

....

//And then allocating space for elements, which will get called an unknown amount of times
Thing j;
thingarray[count] = j;

How do I set up malloc and realloc to be able to add as many elements of type Thing to the array of "Thing"?


Solution

  • You'll probably want to use the dynamic array strategy: keep track of how many items are in it and the current capacity, then any time it fills up, double the capacity. You get amortized linear time and the random access of an array.