We have two types of memory management operators in the C++ language. They are:
These memory management operators are used in allocating and freeing memory blocks efficiently and conveniently.
In C++ language, the new operator is used for dynamic storage allocation. It can be used to create an object of any type.
Syntax:
pointer_variable = new data-type
Example:
int *count;
count = new int;
'count' is a pointer of type int.
Delete is used when our variable is not required in next step, then its a good practice to release that allocated space. That space can be used by other variable.
Syntax:
delete pointer_variable;
In the above syntax 'delete' is the operator which is used to delete the existing object, and 'pointer_variable' is the name of the pointer variable.
Example:
#include <iostream>
using namespace std
int main()
{
int size; // variable declaration
int *arr = new int[size]; // creating an array
cout<<"Enter the size of the array : ";
std::cin >> size; //
cout<<"nEnter the element : ";
for(int i=0;i<size;i++) // for loop
{
cin>>arr[i];
}
cout<<"nThe elements that you have entered are :";
for(int i=0;i<size;i++) // for loop
{
cout<<arr[i]<<",";
}
delete arr; // deleting an existing array.
return 0;
}