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