views:

99

answers:

2

So I need to have an array of structs in a game I'm making - but I don't want to limit the array to a fixed size. I'm told there is a way to use realloc to make the array bigger when it needs to, but can't find any working examples of this.

Could someone please show me how to do this?

Thanks!

+1  A: 

From http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/

/* realloc example: rememb-o-matic */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int input,n;
  int count=0;
  int * numbers = NULL;

  do {
     printf ("Enter an integer value (0 to end): ");
     scanf ("%d", &input);
     count++;
     numbers = (int*) realloc (numbers, count * sizeof(int));
     if (numbers==NULL)
       { puts ("Error (re)allocating memory"); exit (1); }
     numbers[count-1]=input;
  } while (input!=0);

  printf ("Numbers entered: ");
  for (n=0;n<count;n++) printf ("%d ",numbers[n]);
  free (numbers);

  return 0;
}
Pavel Radzivilovsky
Bad Pavel! No posting somebody else's code! No cookie! :)
Nikolai N Fetissov
I gave reference, which makes it a cookie, no?
Pavel Radzivilovsky
+2  A: 

Start off by creating the array:

structName ** sarray = (structName **) malloc(0 * sizeof(structName *));

Always keep track of the size separately:

long sarray_len = 0;

To increase or truncate:

sarray = (structName **) realloc(sarray, (sarray_len + offset) * sizeof(structName *));

Then set the size:

sarray_len += offset;

Happy to help and hope that helps.

Delan Azabani
that's exactly what i was after, thanks.
Gary