Reputation: 121
Using c, I'm trying to input stuff into an array of structs, and once that array is filled, double the size of the array and keep going, using realloc.
I know there's been several question like this asked already, but I was hoping someone could explain it clearly since I didn't create my array the way those questions did and am getting a bit confused.
I have a struct
struct Data {
// Some variables
}
and initialised the array using
struct Data entries[100];
int curEntries = 100;
int counter = 1; // index, I use (counter - 1) when accessing
To realloc, I'm currently using
if(counter == curEntries){ // counter = index of array, curEntries = total
entries = realloc(entries, curEntries * 2);
}
I know I need to cast realloc to something right? I'm just not sure how or what I'm meant to be casting it to, so I currently don't have anything, which of course gives me the error "assignment to expression with array type"
Thanks!
Upvotes: 1
Views: 3526
Reputation: 4044
struct Data entries[100];// memory is already allocated to this
You need to declare entries
as pointer like:
struct Data *entries=NULL;
entries = malloc(curEntries * sizeof(struct Data));
//When its time to reallocate
entries = realloc(entries, (curEntries * 2 * sizeof(struct Data)));
Upvotes: 3