#include<iostream>
using namespace std;
int main(){
///操作符new
//声明一个整型指针变量
int*y;
//为这个整数动态分配存储空间
y=new int;
//要在动态分配的空间中存储一个值
*y=10;
//可以将以上三个步骤合并为
int*y=new int;
*y=10;
//或者
int *y=new int(10);
//或者
int *y;
y=new int (10);
//一个长度为n的一维浮点数组可以按如下方式创建,访问可以通过x[i]
int n=6;
float *x=new float[n];
//异常处理
float*x;
try{x=new float[n];}
catch(bad_alloc e)
{//仅当new失败时才会进入
cout<<"Out of the memory"<<endl;
exit(1);
}
///操作符delete,释放所分配的空间
delete y;
delete []x;
///分配二维数组,列数确定为5
char(*c)[5];
try{c=new char[n][5];}
catch(bad_alloc){
cout<<"Out of the memory"<<endl;
exit(1);
}
}
//为一个二维数组分配存储空间
template<class T>
bool make2dArray(T**&x,int numofrows,int numofcols)
{//创建一个二维数组
try{
//创建行指针
x=new T* [numofrows];
for(int i=0;i<numofrows;i++){
x[i]=new int [numofcols];
}
return true;
}
catch(bad_alloc)return false;
}
//创建一个二维数组,没有异常处理
template <class T>
void make2darray(T**&x,int numofrows,int numofcols){
x=new T*[numofrows];
for(int i=0;i<numofrows;i++){
x[i]=new int [numofcols];
}
}
//释放在函数make2darray中的空间
template<class T>
void delete2darray(T**&x,int numofrows){
for(int i=0;i<numofrows;i++){
delete []x[i];
}
//删除行指针
delete []x;
x=NULL;
}
cpp内存动态分配,new与delete
最新推荐文章于 2024-09-12 19:02:20 发布