C: Expanding an array with malloc C: Expanding an array with malloc arrays arrays

C: Expanding an array with malloc


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.   }


You want to use realloc (as other posters have already pointed out). But unfortunately, the other posters have not shown you how to correctly use it:

POINTER *tmp_ptr = realloc(orig_ptr, new_size);if (tmp_ptr == NULL){    // realloc failed, orig_ptr still valid so you can clean up}else{    // Only overwrite orig_ptr once you know the call was successful    orig_ptr = tmp_ptr;}

You need to use tmp_ptr so that if realloc fails, you don't lose the original pointer.


No, you can't. You can't change the size of an array on the stack once it's defined: that's kind of what fixed-size means. Or a global array, either: it's not clear from your code sample where myarray is defined.

You could malloc a 1000-element array, and later resize it with realloc. This can return you a new array, containing a copy of the data from the old one, but with extra space at the end.