关于new及delete的总结

参考1https://blog.csdn.net/stefanjoe/article/details/79815959
参考2https://blog.csdn.net/hit_shaoqi/article/details/103348024?utm_medium=distribute.pc_relevant_download.none-task-blog-baidujs-2.nonecase&depth_1-utm_source=distribute.pc_relevant_download.none-task-blog-baidujs-2.nonecase

1.定义一个整数

    int *p=new int; //申请一个int类型大小的空间地址给p
    int *p=new int(3); //申请空间的同时赋初值3
    delete p;//释放单变量空间

2.定义一个数组

	int *p=new int[10]; //未初始化
    int *p=new int[10]{1,2,3,4,5,6,7,8,9,10};//初始化
    delete[] p;//注意删除数组时,要在delete后添加[]

注意:删除数组空间时,要在delete后加[ ]

3.定义二维数组

//方式1
    int (*array)[n] = new int[m][n]; 
    delete []array;  // in c++11: auto array = new int[m][n]
//方式2
    int** array = new int*[m]; 
    for(i) 
    array[i] = new int[n];  
    for(i) delete []array[i]; 
    delete []array;   // 多次析构,不建议使用
//方式3
    int* array = new int[m*n];  
    delete []array;      //数组按行存储
 //C++11的新特性
 	auto array = new int[m][n];
 	delete []array;
 	
//注意这种方式不可用: int **array = new int[m][n];

建议采用第一种即可,记得太多反而混乱,先学会一种,其他几种了解,看懂即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值