C: Expanding an array with malloc

49,570

Solution 1

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

Solution 2

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.

Solution 3

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.

Solution 4

a) you did not use malloc to create it so you cannot expand with malloc. Do:

  mystruct *myarray = (mystruct*)malloc(sizeof( mystruct) *SIZE);

b) use realloc (RTM) to make it bigger

Share:
49,570
Admin
Author by

Admin

Updated on November 11, 2020

Comments

  • Admin
    Admin over 3 years

    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.

    Example:

    #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)