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; }
(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)
In this tutorial, you'll learn to dynamically allocate memory in your C program using standard library functions: malloc(), calloc(), free() and realloc(). As you know, an array is a collection of a fixed number of values. Once the size of an array is declared, you cannot change it.
Arrays are continuous in memory, so can't be resized. Arrays however have O(1) access time, so this is the advantage of that. Vectors are resizable, but are slower than arrays. If you have to resize your array, the only way to do it is create a new array of the new size, then copy over all the data from the old array.
We can create an array of pointers also dynamically using a double pointer. Once we have an array pointers allocated dynamically, we can dynamically allocate memory and for every row like method 2.
To dynamically allocate space, use calls to malloc passing in the total number of bytes to allocate (always use the sizeof to get the size of a specific type). A single call to malloc allocates a contiguous chunk of heap space of the passed size.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With