How to dynamically increase the array size?

   int* newArr = new int[new_size];
   std::copy(oldArr, oldArr + std::min(old_size, new_size), newArr);
   delete[] oldArr;
   oldArr = newArr;

You can't change the size of the array, but you don't need to. You can just allocate a new array that's larger, copy the values you want to keep, delete the original array, and change the member variable to point to the new array.

  1. Allocate a new[] array and store it in a temporary pointer.

  2. Copy over the previous values that you want to keep.

  3. Delete[] the old array.

  4. Change the member variables, ptr and size to point to the new array and hold the new size.

Tags:

C++