cpp内存动态分配,new与delete

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值