Node is saved as draft in My Content >> Draft
-
Dynamic memory in C++
The allocation of memory is the crucial factor for any application.
We allocate memory for variables and objects.
We can perform memory allocation in the following two ways:
We have data type which will allocate the memory at runtime. The new keyword is used for it.
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
double* pvalue = NULL;
if( !(pvalue = new double ))
{
cout << "Error: out of memory." <<endl;
exit(1);
}
Dynamic Memory Allocation for Arrays:
char* pvalue = NULL; // Pointer initialized with null
pvalue = new char[20]; // Request memory for the variable
Dynamic Memory Allocation for Objects:
#include <iostream>
using namespace std;
class Box
{
public:
Box() {
cout << "Constructor called!" <<endl;
}
~Box() {
cout << "Destructor called!" <<endl;
}
};
int main( )
{
Box* myBoxArray = new Box[4];
delete [] myBoxArray; // Delete array
return 0;
}
0 Comment(s)