How do I allocate more space for my array of C structs?

Josh picture Josh · Oct 31, 2010 · Viewed 10.9k times · Source

I'm trying to add 10 more elements to my struct that has been already malloc with a fixed sized of 20. This is the way I have my struct defined:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct st_temp {
   char *prod;
};

int main ()
{
   struct st_temp **temp_struct;

   size_t j;
   temp_struct = malloc (sizeof *temp_struct * 20);
   for (j = 0; j < 20; j++) {
      temp_struct[j] = malloc (sizeof *temp_struct[j]);
      temp_struct[j]->prod = "foo";
   }

   return 0;
}

So what I had in mind was to realloc as (however, not sure how to):

temp_struct = (struct st_temp **) realloc (st_temp, 10 * sizeof(struct st_temp*));

and then add the extra 10 elements,

   for (j = 0; j < 10; j++)
      temp_struct[j]->prod = "some extra values";

How could I achieve this? Any help is appreciated!

Answer

Greg Hewgill picture Greg Hewgill · Oct 31, 2010

When you use realloc(), you must give the new size instead of the number of bytes to add. So:

temp_struct = (struct st_temp **) realloc (temp_struct, 30 * sizeof(struct st_temp*));

30 is, of course, your original 20 plus 10 more. The realloc() function takes care of copying the original data to a new location if it needs to move the memory block.

Then, adding the extra 10 elements would be something like (starting at index 20, not 0):

for (j = 20; j < 30; j++) {
    temp_struct[j]->prod = "some extra values"; 
}