c语言中提供了malloc 和free 两个系统函数,完成对堆内存的申请和释放。而c++则提供了两关键字 new 和delete ;
new/new[]用法:
开辟单变量地址空间
- int *p = new int; //开辟大小为sizeof(int)空间
- int *a = new int(5); //开辟大小为sizeof(int)空间,并初始化为5
开辟数组空间
- 一维: int *a = new int[100]{0};//开辟一个大小为100的整型数组空间
int *p = new int[5]{NULL}
- 二维: int (*a)[6] = new int[5][6]
- 三维: int (*a)[5][6] = new int[3][5][6]
- 四维维及其以上:依此类推.
delete /delete[]用法:
1. int *a = new int;
delete a; //释放单个int的空间
2.int *a = new int[5];
delete []a; //释放int数组空间
综合用法:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <typeinfo>
using namespace std;
int main()
{
int *p = new int(5);
cout<<*p<<endl;
delete p;
char *pp = new char[10];
strcpy(pp,"china");
cout<<pp<<endl;
delete []pp;
string *ps = new string("china");
cout<<*ps<<endl; //cout<<ps<<endl;
delete ps;
char **pa= new char*[5];
memset(pa,0,sizeof(char*[5]));
pa[0] = "china";
pa[1] = "america";
char **pt = pa;
while(*pt)
{
cout<<*pt++<<endl;
}
delete []pt;
int (*q)[3] = new int[2][3];
for(int i=0; i<2; i++)
{
for(int j=0; j<3; j++)
{
q[i][j] = i+j;
}
}
for(int i=0; i<2; i++)
{
for(int j=0; j<3; j++)
{
cout<<q[i][j];
}
cout<<endl;
}
delete []q;
int (*qq)[3][4] = new int [2][3][4];
delete []qq;
}
注意事项:
1,new/delete 是关键字,效率高于malloc和free.
2,配对使用,避免内存泄漏和多重释放。
3,避免,交叉使用。比如malloc申请的空间去delete,new出的空间被free;