您的位置:首页 > 其它

堆申请(new)与堆释放(delete)

2017-12-01 10:18 134 查看

堆申请(new)与堆释放(delete)

#include "stdafx.h"
#include <iostream>
using namespace std;

#include <string>

//malloc free #include <stdlib.h> 库函数
//new delete    关键字(key work)

int _tmain(int argc, _TCHAR* argv[])
{

#if  0

----单变量空间的申请:

int* p=new int(200); new的同时进行初始化
//开辟大小为 sizeof(int)空间,并初始化为200
cout<<*p<<endl;

//int* p=(int*)malloc(sizeof(int));

string *ps = new string("purple palace");
//*ps="china";
cout << *ps << endl;

struct Stu
{
int age;
string name;
};

Stu* pstu = new Stu{ 10, "bob" }; //初始化结构体用大括号{}

#endif

#if 0
----数组申请

char* p=new char[40];
strcpy(p,"china"); //注意strcpy的参数为char*类型
cout<<p<<endl;

int* pi=new int[5]{0};
memset(pi, 0, sizeof(int[5])); //数组的初始化函数

char** ppc = new char*[5]{NULL}; //new一个字符指针数组
ppc[0] = new char[10]; //别忘了多delete一次
strcpy(ppc[0], "china");
ppc[1] = "greatWall";
ppc[2] = "wangmeng";

while (*ppc)
{
cout << *pcc++ << endl;
}

int(*pa)[4] = new int[3][4]{{0}};//初始化
for(int i=0;i<sizeof(int[3][4])/sizeof(int[4]);i++)
{
for(int j=0;j<4;j++)
{
cout<<pa[i][j]<<" ";
}
cout<<endl;
}

//利用malloc申请二维数组
//int a[2][3];
//int(*p)[3] = (int(*)[3])malloc(2 * 3 * 4);

#endif

//int* p = new int;
//delete p;

//int* q = new int[100];
//delete []q;

int(*q)[3] = new int[2][3];
delete[]q;

int b[2][3][4];
int(*p)[3][4] = new int[2][3][4];// 前面类型错了会有提示
delete[]p; //不管几维数组 delete一个[]就可以

char* x = (char*)malloc(100);
if (x == NULL)//判断malloc异常
return -1;

char* y = new char[100]; //正常情况下不用判断new的异常
//C++提供了异常的判断方法, 但工作中几乎用不到

return 0;
}

new delete 与构造器 析构器的联系

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: