#include<bits/stdc++.h>
using namespace std;
/**
* new 和 delete 分配和释放堆内存
* */
int main() {
int *p1, *p2, *p3;
p1 = new int ; // 分配能够存储 int 类型的内存区域
p2 = new int(10); // 分配 int 类型的内存区域,并且初始化为 10
p3 = new int[10]; // 分配能够存放 10 个整数的数组区域
if(!p3) { // 分配不成功,显示错误信息
cout<<"allocation failture"<<endl;
return -1; // 返回错误状态码
}
*p1 = 5;
*p3 = 1;
p3[1] = 2; // 访问指向数组的元素
p3[2] = 3;
cout<<"p1 address:" << p1 << " value:"<< *p1 <<endl;
cout<<"p2 address:" << p2 << " value:"<< *p2 <<endl;
cout<<"p3[0] address" << p3 << " value:" << *p3<<endl;
cout<<"p3[1] address" << &p3[1] << " value:" << p3[1]<<endl;
delete p1;
delete p2;
// delete p3; // 错误,只释放了 p3 指向数组的第一个元素,会造成内存泄露
delete []p3;
return 0;
}