Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: What is the proper way of resizing a dynamically allocated array?

Tags:

c++

arrays

resize

In C, I would have done it using realloc.

In C++, one would normally consider using the STL vector class.

But how do I properly resize an array in C++ without using any of the above solutions?

like image 750
Jarx Avatar asked Mar 20 '11 20:03

Jarx


People also ask

How do I get the size of a dynamic array in C++?

In C++, we use sizeof() operator to find the size of desired data type, variables, and constants. It is a compile-time execution operator. We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);

What is dynamic resizing?

Suggest Edits. In addition to resizing images using hard coded dimensions, you can use Image and Video Manager to dynamically resize images based on published dimensions.


1 Answers

There is no good equivalent of realloc in C++. You'll need to manually duplicate the array and copy the old elements over. Fortunately, thanks to the std::copy function in <algorithm>, this isn't too bad:

size_t k =  /* ... */
T* buffer = /* .. get old buffer of size k. .. */

T* newBuffer = new T[newSize];  // Assume newSize >= k
std::copy(buffer, buffer + k, newBuffer);

delete [] buffer;
buffer = newBuffer;

Hope this helps!

EDIT: Reordered the last two lines! Whoops!

like image 148
templatetypedef Avatar answered Sep 27 '22 22:09

templatetypedef