2

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?

3
  • This h = malloc(sizeof(int)); allocates only an int Commented Nov 7, 2015 at 23:13
  • your only allocating space for h[0] and leaking the previous h Commented Nov 7, 2015 at 23:13
  • 2
    A pointer is no array! Commented Nov 7, 2015 at 23:59

1 Answer 1

2

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(); } 
Sign up to request clarification or add additional context in comments.

3 Comments

Can I ask another question: How do I determine the size of h? I mean when I want to search for an element in h, I need the size for h to iterate over it, right?
There is no library support for that in C. Your code will need to remember the largest value of i for which h[i] is meaningful data. (This is not the same as avail in my sample code.)
Thanks alot ... appreciate it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.