美文网首页
动态数组的分配与释放

动态数组的分配与释放

作者: 猩猩隊長 | 来源:发表于2018-12-22 22:57 被阅读0次
    一维数组
    int m = 5;
    int *arr = new int [m];
    delete [] arr;
    
    二维数组
    #include <iostream>
    using namespace std;
    
    int main() 
    {
        int m = 5, n = 10, v = 0;
    
        //创建指针数组
        int **arr = new int* [m];
    
        //为指针数组的每个元素创建一个一维数组,得到arr[m][n]
        for (int i = 0; i < m; i++)
        {
            arr[i] = new int[n];
        }
    
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                arr[i][j] = v;
                v++;
            }
        }
    
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                cout << arr[i][j] << " ";
            }
            cout << endl;
        }
    
        //使用后先删除一维数组
        for (int i = 0; i < m; i++)
        {
            delete [] arr[i];
        }
    
        //再删除指针数组
        delete arr;
    
        //也可以直接delete [] arr;
    
        return 0;
    }
    
    三维数组
    int ***array3D;
    int m = 5, n = 10, h = 20;
    
    arr = new int **[m];
    for( int i=0; i<m; i++ )
    {
        arr[i] = new int *[n];
        for( int j=0; j<n; j++ )
        {
             arr[i][j] = new int [h];
        }
    }
    //释放
    for( int i=0; i<m; i++ )
    {
        for( int j=0; j<n; j++ )
        {
             delete arr[i][j];
        }
        delete arr[i];
    }
    delete arr;
    

    相关文章

      网友评论

          本文标题:动态数组的分配与释放

          本文链接:https://www.haomeiwen.com/subject/rkawkqtx.html