24C. Reallocating an Array (Optional)

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

  1. create a new chunk,
  2. copy the contents of the old chunk into the new chunk,
  3. delete the old chunk,
  4. make your pointer variable point to the new chunk.

For example, the following function takes a variable A, a pointer passed by reference, a size oldsize telling how large A's chunk is currently, and a size newsize telling how large the new chunk is desired to be. It changes A to point to the new chunk. (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, const int oldsize, const 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;
  }

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

ReallocateArray assumes that A points to a chunk that is in the heap. It will not work if A's chunk 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 a chunk of that size is created. Changing a variable that was used to compute the size has no effect on the size of the chunk. For example, after
  int n = 20;
  int A[n];
  n++;
array A still has size 20. Changing n to 21 does not magically cause A to grow.