int main(int argc, char* argv[])
{
//----------------------------------------------------------------
// Initialization
//----------------------------------------------------------------
int array_size = 100; // set initial size of the memory block
//----------------------------------------------------------------
// Allocate memory pointed by dynamic_memory
//----------------------------------------------------------------
int* dynamic_memory = new int[ array_size ]; // allocate memory
int idx = 0;
for ( ; idx < array_size; ++idx ) {
// use allocated memory:
// store sequence of numbers 0,1,2,...,99
dynamic_memory[ idx ] = idx;
}
//----------------------------------------------------------------
// Re-allocate memory (we need more!)
//----------------------------------------------------------------
array_size = array_size * 2; // double the size of the memory block
int* temp_reallocate = new int[ array_size ]; // allocate more memory
for ( idx = 0; idx < array_size / 2; ++idx ) {
// move data from the old block to the new one:
temp_reallocate[ idx ] = dynamic_memory[ idx ];
}
// Free old memory so that the memory becomes available
// again for future requests of dynamic memory:
delete[] dynamic_memory;
dynamic_memory = temp_reallocate; // memory re-allocation complete!
// Continue using dynamic memory...
//----------------------------------------------------------------
// Finally, de-allocate dynamic memory:
//----------------------------------------------------------------
delete[] dynamic_memory;
return 0;
}