The only way to create arrays that have a size that can be dynamically changed is with vectors. |
Er, do you know how the STL vector works?
Technically (according to the C++ standard), you can't change the size
any array, but (according to the OS) you may request a resize or reallocate dynamically allocated memory (which C++ can treat like an unbounded array).
The C dynamic memory functions provide for resize/reallocate requests, but C++ does not directly. You should reallocate something like this:
1 2 3 4 5 6
|
{
int *newarray = new int[newsize];
std::copy( array, array+std::min(oldsize,newsize), newarray );
delete [] array;
array = newarray;
}
|
You may notice that this is, technically,
not a reallocation, but a relocation. That is, it creates a
new array and copies the data from the old over to the new, and destroys the old.
The STL
vector class does just this, with one more optimization: it allocates
more than is necessary so that there is room to grow before having to 'reallocate', and simply keeps track of exactly how much of the array is currently used.
Hope this helps.