|
|
|
Dynamic Memory Allocation
% cat dyn_mem.cpp
// dynamic memory allocatiom
#include <iostream>
using namespace std;
#include <cstdlib>
int main()
{
int num_points, i;
cout << "Enter the number of data points to be entered: ";
cin >> num_points;
// allocate memory for the array
int *points = new int[num_points];
// verify that space was available
if( points == 0 )
{
cout << "\n Memory not available. \n";
exit(1);
}
// get data
for(i = 0; i < num_points; i++)
{
cout << " Enter a data value: ";
cin >> *(points + i);
// use pointer notation
}
cout << "\nAn array was created for " << num_points
<< " data points\n";
cout << " The data values entered are:";
for (i = 0; i < num_points; i++)
cout << "\n " << points[i];
cout << endl;
delete [] points; // return the storage to the freestore
return 0;
}
% g++ dyn_mem.cpp
% a.out
Enter the number of data points to be entered: 3
Enter a data value: 2
Enter a data value: 3
Enter a data value: 7
An array was created for 3 data points
The data values entered are:
2
3
7
% a.out
Enter the number of data points to be entered: 5
Enter a data value: 2
Enter a data value: 4
Enter a data value: 6
Enter a data value: 8
Enter a data value: 10
An array was created for 5 data points
The data values entered are:
2
4
6
8
10
|
|