English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The delete operator is used to release allocated memory. The user has the privilege to release the allocated pointer variable through this delete operator.
This is C ++The syntax of delete operator in language
delete pointer_variable;
This is the syntax for deleting allocated memory block
delete[ ] pointer_variable;
This is C ++Example of delete operator in language
#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 result
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, one of which is a pointer variable* p, it stores the memory allocated by malloc. The elements of the array are printed by the user, and the sum of the elements is printed. To delete the allocated memory, please use delete ptr1, delete pt2and delete [] ptr3.
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;