Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically increase/decrease array size

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?

like image 716
Florian Avatar asked May 22 '13 10:05

Florian


People also ask

How to increase the size of an array of structures?

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:

How do I change the size of an array in C++?

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.

How do I resize an array of variables dynamically?

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.

How to allocate memory more efficiently for large arrays?

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.


1 Answers

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.

like image 163
JBL Avatar answered Oct 16 '22 09:10

JBL