您的位置:首页 > 编程语言 > C语言/C++

qt开发环境 - c++动态内存

2017-08-15 22:32 393 查看
#include <QCoreApplication>
#include <iostream>

using namespace std;

struct Student{
string name;
int age;
};

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int* p1 = new int;
*p1 = 666;
++*p1;
cout << *p1 << endl;
delete p1;
p1 = NULL;
p1 = new int();//默认是0
cout << *p1 << endl;
delete p1;
p1 = NULL;
p1 = new int(666);//默认是666
cout << *p1 << endl;
delete p1;
p1 = NULL;
delete p1;//不会出错,delete会自动检查 是不是空
//    *p1 = 233;
p1 = new int[4]{1,2,3,4};
cout << p1[0] << p1[1] << p1[2] << p1[3]<< endl;
delete[] p1;
//    p1 = new int[0xFFFFFFFF];
try{
p1 = new int[/*0xFFFFFFFF*/3];
//成功,访问内存(可以在这里)
//delete[] p1;
//p1 = NULL;
}
catch(exception& ex){
cout << ex.what() << endl;
cout << "动态内存分配失败" << endl;
return -1;
}
//成功,访问内存(也可以在这里)
//delete[] p1;
//p1 = NULL;
int (*p2)[4] = new int[3][4];//4是内层结构
p2[0][0] = 2;
cout << p2[0][0] << endl;
delete[] p2;
int (*p3)[4][5] = new int[3][4][5];
p3[0][0][1] = 777;
cout << p3[0][0][1] << endl;
delete[] p3;
string* p4 = new string;
cout << '[' << *p4 << ']' << endl;
delete p4;
p4 = new string("ayumi hamasaki");
cout << '[' << *p4 << ']' << endl;
delete p4;
p4 = new string[3]{"I ","love ", "ayumi"};
cout << p4[0] << p4[1] << p4[2] << endl;
delete p4;
Student* p5 = new Student;
p5->name = "ayu";
p5->age = 33;
cout << p5->name << p5->age << endl;
delete p5;
return a.exec();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: