I'm trying to increase the size of an array dynamically. Is there any standard C or C++ function, which appends additional space at the end of an array or removes it? I know, this is difficult, since it cannot be assured that there is enough space at the end on the heap. But shouldn't this be the job of an operating system?
You will need to use the malloc and realloc functions from <stdlib.h> for this. The basic idea is to allocate a certain amount of space up front, and then enlarge the array when you discover that it is not big enough. It will make life easier if you use an array of structures rather than an array of arrays:
Technically (according to the C++ standard), you can't change the size any array, but (according to the OS) you may request a resize or reallocate dynamically allocated memory (which C++ can treat like an unbounded array). The C dynamic memory functions provide for resize/reallocate requests, but C++ does not directly.
Adding and reducing variables on an array dynamically is a huge advantage for when the information you are treating does not have a set number of variables. You can simply resize the Array with the ReDim Statement, this will resize the array but to if you which to retain the information already stored in the array you'll need the part Preserve.
This is acceptable for small array sizes, but it quickly adds up. There are multiple techniques to allocate memory more efficiently. One of the techniques is to allocate enough memory to hold the largest array that you might ever need, and then when you turn out to use less, to throw away the extra.
The function you're looking for is realloc()
in C, which is also present in the C++ STL as std::realloc
Though as you mentioned C++, you could also go for an standard container like std::vector
which encapsulate the associated memory management.
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