Mal Ock Mal Ock - 4 months ago 27
C Question

C: Expanding an array with malloc

I'm a bit new to malloc and C in general. I wanted to know how I can, if needed, extend the size of an otherwise fixed-size array with malloc.


#define SIZE 1000
struct mystruct
int a;
int b;
char c;
mystruct myarray[ SIZE ];
int myarrayMaxSize = SIZE;
if ( i > myarrayMaxSize )
// malloc another SIZE (1000) elements
myarrayMaxSize += SIZE;

  • The above example should make clear what I want to accomplish.

(By the way: I need this for an interpreter I write: Work with a fixed amount of variables and in case more are needed, just allocate them dynamically)


Use realloc, but you have to allocate the array with malloc first. You're allocating it on the stack in the above example.

   size_t myarray_size = 1000;
   mystruct* myarray = malloc(myarray_size * sizeof(mystruct));

   myarray_size += 1000;
   mystruct* myrealloced_array = realloc(myarray, myarray_size * sizeof(mystruct));
   if (myrealloced_array) {
     myarray = myrealloced_array;
   } else {
     // deal with realloc failing because memory could not be allocated.