I have a struct called Collection:
typedef struct collection {
char *type;
char *arg;
} *Collection;
And I would like to have a dynamic array of this struct (or rather, of pointers to instances of this struct). This is what I tried:
Collection *rawCollections = malloc(0);
int colCounter = 0;
while (i < argc) {
Collection col = malloc(sizeof(Collection));
// code to fill in Collection
rawCollections = realloc(rawCollections, sizeof(rawCollections) + sizeof(Collection));
rawCollections[colCounter] = col;
colCounter++;
}
My reasoning is that we will add sizeof(Collection) to the array each time I need to add another one. I am getting these errors, and I am not sure why:
realloc(): invalid next size
Aborted (core dumped)
sizeof(rawCollections)does not change.colCounter).Collection col = malloc(sizeof(Collection));is also wrong.Collectionis a typedef ofstruct collection *. So you are creating a variable of typestruct collection *and pointing it to memory allocated to be the size ofstruct collection *. That is, you allocated the size of a pointer when you should have allocated the size of the object being pointed to. You can fix that by turning themalloccall intomalloc(sizeof(*col))