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
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. |