• C plus 内存管理


    int *y = new int; *y = 10;

    或者 int *y = new int (10);

    或者 int *y; y = new int (10);

     

    一维数组: float *x = new float [n];

     

    在Borland C++中,当new 不能分配足够的空间时,它会引发(t h r o w)一个异常xalloc (在except.h 中定义)。可以采用try - catch 结构来捕获(c a t c h)new 所引发的异常:

    float *x;
    try {x = new float [n];}
    catch (xalloc) {

              // 仅当new 失败时才会进入
              cerr << "Out of Memory"  << endl;
              e x i t ( 1 ) ;  //exit () 在stdlib.h 中定义

    }

     

    释放内存:

    delete y;
    delete [ ] x;

     

    如果在编译时至少有一维是未知的,必须在运行时使用操作符n e w来创建该数组;

    char (*c)[5];
    try { c = new char [n][5];}
    catch (xalloc) {

                //仅当n e w失败时才会进入
                 cerr << "Out of Memory"  << endl;
                 exit (1);

    }

    为一个二维数组分配内存空间:

    template <class T>
    bool Make2DArray ( T ** &x, int rows, int cols){
    	// 创建一个二维数组
    	t r y {
    		/ /创建行指针
    		x = new T * [rows];
    		/ /为每一行分配空间
    
    		for (int  i = 0 ; i < rows; i++)
    			{ x[i] = new int [cols];}
    		return true;
    	}
    	catch (xalloc) {return false;}
    }
    
    
    不报错
    

    template <class T>
    void Make2DArray( T ** &x, int rows, int cols){

                 // 创建一个二维数组
                // 不捕获异常
               / /创建行指针
               x = new T * [rows];
               / /为每一行分配空间
               for (int i = 0 ;  i<rows; i++)
                                 x[i] = new int [cols];

    }

    try { Make2DArray (x, r, c);}
    catch (xalloc) {

              cerr<< "Could bot create x" << endl;
              e x i t ( 1 ) ;

    }

    在M a k e 2 D A r r a y中不捕获异常不仅简化了函数的代码设计,而且可以使用户在一个更合适
    的地方捕获异常,以便更好地报告出错误的明确含义或进行错误恢复

     

    释放空间:


  • 相关阅读:
    python Flask JQuery使用说明
    sqlserve 数据类型具体解释
    赵雅智_ListView_SimpleAdapter
    HDU 1018 Big Number (log函数求数的位数)
    cocos2d函数
    BZOJ 3514 Codechef MARCH14 GERALD07加强版 Link-Cut-Tree+划分树
    QQ好友列表数据模型封装
    【Codeforces】512C Fox and Dinner
    spring中操作mysql数据库
    【读书笔记】iOS-Xcode-模拟器操作的一些快捷键
  • 原文地址:https://www.cnblogs.com/buttonwood/p/2518637.html
Copyright © 2020-2023  润新知