C ++中的delete()运算符
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;热门推荐
10 长辈乔迁送花祝福语简短
11 满月红包英文祝福语简短
12 毕业祝福语保安文案简短
13 朋友祝福语两字简短
14 母亲贺卡生日祝福语简短
15 婚礼仪式祝福语简短
16 幽默小姐姐祝福语简短
17 表妹结婚祝福语简短藏语
18 生日祝福语男孩 简短独特