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

#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();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值