Reputation: 390
Suppose we have this code:
int *h;
for(int i=0;i<5;i++){
h = malloc(sizeof(int));
h[i] = i;
}
The issue I have here is that I want to start with an empty array, i.e. just declaringint *h
, and then *h
will grow at the runtime using realloc
. I tried using this example but it does not allocate a sequential memory places and also does not work. I understand that realloc
works after allocating by malloc so is there any workaround of that?
Upvotes: 2
Views: 53
Reputation: 140445
To accommodate exactly what you are trying to do, realloc(NULL, size)
does the same thing as malloc(size)
. You can write your loop like this:
int *h = 0;
size_t avail = 0;
for (size_t i = 0; more_data_available(); i++) {
if ((i+1) * sizeof(int) > avail) {
avail = avail == 0 ? 8*sizeof(int) : avail*2;
int *nh = realloc(h, avail);
if (!nh) abort();
h = nh;
}
h[i] = next_data_item();
}
But note the convoluted ?:
expression I had to use to enlarge avail
. That would be cleaner if I start the loop with some space already allocated; and then I can just use malloc
normally:
size_t avail = 8 * sizeof(int);
int *h = malloc(avail);
if (!h) abort();
for (size_t i = 0; more_data_available(); i++) {
if ((i+1) * sizeof(int) > avail) {
avail *= 2;
int *nh = realloc(h, avail);
if (!nh) abort();
h = nh;
}
h[i] = next_data_item();
}
Upvotes: 2