如何动态开辟2d array 以及如何删除所开辟的空间。

作者在 2006-10-27 12:59:00 发布以下内容
今天看到了一位网友提的问题中涉及了动态开辟的空间的问题, 这个问题是一再有人提的,而往往很多C++ 书籍没有给出这个问题的解答, 有些书籍给出了动态开辟的代码却忘记了删除所开辟的空间。 就这个问题的解答特写了下面的这个演示代码。

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    int rows = 2;
    int cols = 3;
    
    // create a dynamic array
    int ** array = NULL;
    array = new int * [rows];
    
    
    for(int i = 0; i < rows; i++)
    {
        array = new int[cols];
      
        // init this 2d array
        for(int j = 0; j<cols; j++)
        {
            array[j] = (i+1)*(j+1);
        }    
    }
       
    
    // to check what we have done
    for(int i = 0; i < rows; i++)
    {
        for(int j = 0; j<cols; j++)
        {
            cout<<array[j]<<" ";
        }    
        cout<<endl;
    }        
    
    // before you leave the program
    // you should release the space what you have dynamically allocated
    // to delete the allocation
    for(int i = 0; i<rows; i++)
    {
        delete [] array;
        array = NULL;  //  to avoid wild pointer
    }    
    
    delete [] array;
    array = NULL;  // to avoid wild pointer
      
    system("pause");
    return 0;
}
programming | 阅读 2395 次
文章评论,共0条
游客请输入验证码