Often some situation arises in programming where data or input is dynamic in nature, i.e.
the number of data item keeps changing during program execution. A live scenario where the
program is developed to process lists of employees of an organization. The list grows as the
names are added and shrink as the names get deleted. With the increase in name the memory
allocate space to the list to accommodate additional data items. Such situations in programming
require which technique. Explain the concept with the help of suitable examples.
Such situations in programming require Dynamic Memory allocation technique.
Example :
#include <iostream>
using namespace std;
int main ()
{
int* p = NULL;
p = new(nothrow) int;
if (!p)
cout << "allocation of memory failed\n";
else
{
// Store value at allocated address
*p = 29;
cout << "Value of p: " << *p << endl;
}
float *r = new float(75.25);
cout << "Value of r: " << *r << endl;
int n = 5;
int *q = new(nothrow) int[n];
if (!q)
cout << "allocation of memory failed\n";
else
{
for (int i = 0; i < n; i++)
q[i] = i+1;
cout << "Value store in block of memory: ";
for (int i = 0; i < n; i++)
cout << q[i] << " ";
}
delete p;
delete r;
delete[] q;
return 0;
}
Comments
Leave a comment