How to resize array in C++?

How to resize array in C++?

You cannot resize array, you can only allocate new one (with a bigger size) and copy old arrays contents.
If you dont want to use std::vector (for some reason) here is the code to it:

int size = 10;
int* arr = new int[size];

void resize() {
    size_t newSize = size * 2;
    int* newArr = new int[newSize];

    memcpy( newArr, arr, size * sizeof(int) );

    size = newSize;
    delete [] arr;
    arr = newArr;
}

code is from here http://www.cplusplus.com/forum/general/11111/.

The size of an array is static in C++. You cannot dynamically resize it. Thats what std::vector is for:

std::vector<int> v; // size of the vector starts at 0

v.push_back(10); // v now has 1 element
v.push_back(20); // v now has 2 elements
v.push_back(30); // v now has 3 elements

v.pop_back(); // removes the 30 and resizes v to 2

v.resize(v.size() - 1); // resizes v to 1

How to resize array in C++?

  1. Use std::vector
    or
  2. Write your own method. Allocate chunk of memory using new. with that memory you can expand till the limit of memory chunk.

Leave a Reply

Your email address will not be published.