Dynamic Memory Allocation in C++
If you want to create the memory at run time, this concept is used. This allocation is done by ‘new’ and ‘delete’ operators. This happens in heap memory’s portion.
Let us create a c++ program to display the memory location.
C++ Program:
This
program includes the header files <iostream> and <memory>.
‘main()’ function is included with pointer variable (*ptr)
declaration and assignment of 10
Integer values.
The value and address is printed.
Code:
#include <iostream>
#include <memory>
using namespace std;
int main() {
int *ptr;
ptr = new int(10);
cout <<
"The value is:"<<*ptr << endl;
cout <<
"The address is:"<<ptr;
return 0;
}
Output:
The value is:10
The address is:0x305a32b0
How to allocate memory using ‘new’ operator?
‘new’
operator is used to allocate the memory.
Syntax:
new data_type[n];
Eg:
#include <iostream>
#include <memory>
using namespace std;
int main() {
int *ptr;
ptr = new
int[6]{21, 32, 43, 54, 65,76};
for (int i = 0; i
< 6; i++)
cout <<
ptr[i] << " ";
return 0;
}
Output:
21 32 43 54 65 76
How to use delete operator in C++?
This
operator deallocates the memory at run time. The syntax is given below…
Syntax:
‘delete ptr;’
Program:
#include <iostream>
using namespace std;
int main() {
int *pt = NULL;
pt = new int(5);
int n;
if (!pt) {
cout <<
"allocation of memory failed";
exit(0);
}
cout <<
"Value of *pt: " << *pt << endl;
delete pt;
cout
<<"The memory is deallocated"<<endl;
cout<<"Enter the number of elements for second
array"<<endl;
cin>> n;
pt = new int[n];
cout<<"Enter the elements:"<<endl;
for(int
i=0;i<n;i++)
{
cin>>pt[i];
}
cout <<
"The second Array is created elements are: ";
for (int i = 0; i
< 4; i++)
cout <<
pt[i] <<endl;
cout<<"Finally, the memory is deallocated"<<endl;
delete[] pt;
return 0;
}
Output:
Value of *pt: 5
The memory is deallocated
Enter the number of elements for second array
5
Enter the elements:
23
34
45
56
67
The second Array is created elements are: 23
34
45
56
Finally, the memory is deallocated
Thus the ‘new’ and ‘delete’ operators in dynamic memory
allocation was explained briefly using C++ Programs. Keep Coding!!!
Comments
Post a Comment