5.11.6 Reallocating an Array

If you have an array that is too small or too large, and want to change its size, you will need keep the array as a pointer stored in a variable. Then

  1. create a new array,
  2. copy the contents of the old array into the new array,
  3. delete the old array,
  4. make your pointer variable point to the new array.
For example, the following procedure takes a variable A that points to an array, a size oldsize telling how large A is currently, and a size newsize telling how large the array is desired to be. It changes A to point to the new array. (Note that oldsize is the logical size of A before the reallocation and newsize is the desired physical size of A after the reallocation.)
  void reallocateArray(int*& A, int oldsize, int newsize)
  {
    int* Anew = new int[newsize];
    int  n    = min(oldsize, newsize);

    for(int i = 0; i < n; i++)
    {
      Anew[i] = A[i];
    }
    delete [] A;
    A = Anew;
  }
Notice that A is passed by reference so that it can be changed to point to a new array.

Watch out: reallocation only works for arrays that are in the heap

The reallocateArray procedure above assumes that A points to an array that is in the heap. It will not work if A is stored in the run-time stack, since it does delete [] A.

Watch out: no automatic reallocation

When you create an array, the desired size is computed and an array of that size is created. Changing a variable that was used to compute the size has no effect on the size of the array. For example, after
  int n = 20;
  int A[n];
  n++;
array A still has size 20. Changing n to 21 does not magically cause array A to grow.