delete运算符用于取消分配内存。用户具有通过此delete运算符取消分配创建的指针变量的特权。
这是C ++语言中delete运算符的语法,
delete pointer_variable;
这是删除分配的内存块的语法,
delete[ ] pointer_variable;
这是C ++语言中的delete运算符示例,
#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; }
输出结果
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
在上面的程序中,声明了四个变量,其中之一是指针变量* p,它存储由malloc分配的内存。数组的元素由用户打印,元素的总和打印。要删除那些分配的内存,请使用删除ptr1,删除pt2和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;