delete() operator in C++

C++ProgrammingServer Side Programming

The delete operator is used to deallocate the memory. User has privilege to deallocate the created pointer variable by this delete operator.

Here is the syntax of delete operator in C++ language,

delete pointer_variable;

Here is the syntax to delete the block of allocated memory,

delete[ ] pointer_variable;

Here is an example of delete operator in C++ language,

Example

 Live Demo

#include <iostream>
using namespace std;
int main () {
   int *ptr1 = NULL;
   ptr1 = new int;
   float *ptr2 = new float(299.121);
   int *ptr3 = new int[28];
   *ptr1 = 28;
   cout << "Value of pointer variable 1 : " << *ptr1 << endl;
   cout << "Value of pointer variable 2 : " << *ptr2 << endl;
   if (!ptr3)
   cout << "Allocation of memory failed\n";
   else {
      for (int i = 10; i < 15; i++)
      ptr3[i] = i+1;
      cout << "Value of store in block of memory: ";
      for (int i = 10; i < 15; i++)
      cout << ptr3[i] << " ";
   }
   delete ptr1;
   delete ptr2;
   delete[] ptr3;
   return 0;
}

Output

Value of pointer variable 1 : 28
Value of pointer variable 2 : 299.121
Value of store in block of memory: 11 12 13 14 15

In the above program, four variables are declared and one of them is a pointer variable *p which is storing the memory allocated by malloc. Elements of array are printed by user and sum of elements is printed. To delete those allocated memory, delete ptr1, delete pt2 and delete[] ptr3 are used.

int *ptr1 = NULL;
ptr1 = new int;
float *ptr2 = new float(299.121);
int *ptr3 = new int[28];
*ptr1 = 28;
cout << "Value of pointer variable 1 : " << *ptr1 << endl;
cout << "Value of pointer variable 2 : " << *ptr2 << endl;
if (!ptr3)
cout << "Allocation of memory failed\n";
else {
   for (int i = 10; i < 15; i++)
   ptr3[i] = i+1;
   cout << "Value of store in block of memory: ";
   for (int i = 10; i < 15; i++)
   cout << ptr3[i] << " ";
}
delete ptr1;
delete ptr2;
delete[] ptr3;
raja
Published on 05-Nov-2018 07:35:42
Advertisements