But there may be cases where the memory needs of a program can only be determined during runtime.
For example, when the memory needed depends on user input. On these cases,
programs need to dynamically allocate memory, for which the C++ language integrates the operators
new and delete.
Example: if array size needs to determine by user input that time we need dynamic memory.
In normal array we need to declare the array size at the begining or in compile time.
But in the dynamic memory allocation, user can define array size at the runtime of program
// rememb-o-matic
#include <iostream>
#include <new>
using namespace std;
int main ()
{
int i,n;
int * p;
cout << "How many numbers would you like to type? ";
cin >> i;
p= new (nothrow) int[i];
if (p == nullptr)
cout << "Error: memory could not be allocated";
else
{
for (n=0; n<i; n++)
{
cout << "Enter number: ";
cin >> p[n];
}
cout << "You have entered: ";
for (n=0; n<i; n++)
cout << p[n] << ", ";
delete[] p;
}
return 0;
}
No comments:
Post a Comment