5

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?

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Jarx
  • 51
  • 1
  • 1
  • 2
  • 2
    The proper way to resize a dynamically allocated array in C++ _is_ using a vector. Please tell us you objections to vector (and realloc), so we can respect these in the answers. – Peter G. Mar 20 '11 at 20:46
  • see [c-dynamically-allocating-an-array-of-objects](http://stackoverflow.com/questions/255612/c-dynamically-allocating-an-array-of-objects/255744#255744) – Martin York Mar 20 '11 at 21:28

4 Answers4

8

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!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • @Nawaz- Whoops! That was silly of me. I just updated the code so that it doesn't do that anymore. – templatetypedef Mar 20 '11 at 20:37
  • -1 Incorrect "There is no good equivalent of `realloc` in C++". C++ includes (most of) the C standard library. Including `realloc`. – Cheers and hth. - Alf Mar 20 '11 at 21:58
  • 3
    @Alf P. Steinbach- That's true, but `realloc` is only safe with POD types. If you try `realloc`ing an array of `string`, `vector`, etc. the results are undefined. I probably should have said that there is no good **general** replacement for `realloc`. – templatetypedef Mar 20 '11 at 22:45
3

By doing what vector and realloc do internaly: make a new, bigger array, copy the content of the old one, and destroy the old one.

Nemanja Trifunovic
  • 24,346
  • 3
  • 50
  • 88
0
int* arr = new int[20];
...
//wanna resize to 25?
int* temp = new int[25];
std::copy(arr, arr+20, temp);
delete [] arr;
arr = temp;
... //now arr has 25 elements

But, of course, you shouldn't do this :)

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
0

If you insist on doing this yourself in C++, you probably want to do roughly like std::vector does, and allocate raw memory using the global new operator, then use placement new to create objects "in place".

Otherwise, you end up constructing objects in all the memory you allocate, and then assigning over them when you use them. Unless you know that the initial (default) object construction is lightweight, you'd rather avoid it if possible.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111