/**************************************************************/
// R. A. Hillyard
// pointer05.cpp
// November 2001
//
// Program to demonstrate dynamic arrays
//
// Create a dynamic array and then allow the user to
// adjust the size of the array
/**************************************************************/
#include<iostream>
using namespace std;
int const MinSize = 10;
int main()
{
int *ptr1, *ptr2; //pointer to type int
ptr1 = new int[MinSize]; //point to the first element of the new array
int index; //index variable for counter
int temp;
for(index = 0; index < MinSize; index++) //assign initial values to new array
{ ptr1[index] = 2 * index ; }
for(index = 0; index < MinSize; index++) //print initial value of array elements
{ cout << ptr1[index] << " "; }
cout << "\n\nArray is now "<< MinSize << ": Enter new size >";
cin >> temp;
//save referance to array
ptr2 = ptr1; //ptr2 now points to the first element of the array
ptr1 = new int[temp]; //now create array of new size
if(temp > MinSize) //If new array is larger than MinSize
{
for(index = 0; index < MinSize; index++) //copy all elements of the old array
{ ptr1[index] = ptr2[index]; }
for(index = MinSize; index < temp; index++) //ask for the rest of the elements
{
cout << "enter an int >";
cin >> ptr1[index];
}
delete [] ptr2; //give back the memory
for(index = 0; index < temp; index++) //print new value of array elements
{ cout << ptr1[index] << " "; }
cout << endl;
}//end if
else //new size smaller than old
{
for(index = 0; index < temp; index++) //copy the first temp elements of the array
{ ptr1[index] = ptr2[index]; }
delete [] ptr2; //give back the memory
for(index = 0; index < temp; index++) //print new value of array elements
{ cout << ptr1[index] << " "; }
cout << endl;
}//end else
}
/***********************Program Output*************************/
0 2 4 6 8 10 12 14 16 18
Array is now 10: Enter new size >13
enter an int >5
enter an int >87
enter an int >22
0 2 4 6 8 10 12 14 16 18 5 87 22
/************************Second Run****************************/
0 2 4 6 8 10 12 14 16 18
Array is now 10: Enter new size >7
0 2 4 6 8 10 12