C ++中的2D动态内存分配数组

时间:2013-02-12 09:17:19

标签: c++ dynamic-memory-allocation

几天前,我学会了如何从互联网上创建2D分配的内存阵列,它非常完美。要访问数组,我们只需使用matrix[i][j],但有什么方法可以使用*表示法而不是[]来取消引用此2D数组以进行输入以及其他方法?< / p>

首先解决问题我可以使用*(*(matrix + i) + j)

现在我有了另一个问题,最后一段代码就是释放分配的内存(我也是从互联网上获得的),但是我不明白,为什么我只能使用delete [] matrix

int **matrix;

// dynamically allocate an array
matrix = new int *[row]; 
for (int count = 0; count < row; count++)
{
    matrix[count] = new int[col];
}

// input element for matrix
cout << endl << "Now enter the element for the matrix..."; 
for (int i=0; i < row; i++) 
{
    for (int j=0; j < col; j++)
    {
        cout << endl << "Row " << (i+1) << " Col " << (j+1) << " :";
        cin >> matrix[i][j]; // is there any equivalent declaration here?
    }
}

// free dynamically allocated memory
for( int i = 0 ; i < *row ; i++ )
{
    delete [] matrix[i] ;   
}
delete [] matrix ;

5 个答案:

答案 0 :(得分:5)

回答第二个问题:使用以下代码分配2D数组时

// dynamically allocate an array
    matrix = new int *[row]; 
    for (int count = 0; count < row; count++)
        matrix[count] = new int[col];

实际上你正在分配一个指针数组(你的矩阵变量,它是一个双指针)和整数的“行”数组(每个整数代表矩阵中一行,大小为“col”),它们是{ {1}},matrix[0]等等,直到matrix[1]

因此,当你想要释放你的矩阵时,你首先需要释放每一行(循环中分配的数组),然后释放持有行的数组。在您的情况下,用于释放矩阵的代码部分错误,应该更像以下内容:

matrix[row-1]

循环中的删除将释放矩阵的每一行,最后的删除将释放行数组。在您的代码中,您在双指针(// free dynamically allocated memory for( int i = 0 ; i < row ; i++ ) { //first we delete each row delete [] matrix[i] ; } //finally, we delete the array of pointers delete [] matrix ; )上使用删除row次,这没有任何意义。

最后,在双指针上使用单个删除是错误的,因为它最终会导致内存泄漏,因为您没有释放为每行分配的内存,只有指向它的指针。

答案 1 :(得分:3)

由于a[b]只是*(a + b),您当然可以这样做:

*(*(matrix + i) + j)

无论如何,那些new分配容易出错。如果其中一个嵌套的new抛出,那么你就会有泄漏。请尝试使用std::vector

答案 2 :(得分:2)

这样的事情会起作用:

int **matrix;

// dynamically allocate an array
matrix = new (std::nothrow) int *[row];
if (matrix == NULL)
{
      // handle the error
}
for (int count = 0; count < row; count++)
{
    *(matrix + count) = new (std::nothrow) int[col];
    if (matrix[count] == NULL)
    {
          // handle the error
    }
 }

cout << "\nNow enter the element for the matrix..."; 
for (int i=0; i < row; i++)
{
    for (int j=0; j < col; j++)
    {
        cout << "\nRow " << (i+1) << " Col " << (j+1) << " :";
        cin >> *(*(matrix + i) + j);
    }
}

答案 3 :(得分:1)

是的,您使用指针添加,但您需要了解内存的布局方式。假设x是指向int数组的第一个元素的指针,如果要访问x [2],则可以使用*(x + 2)。但是,对于矩阵,它可能会变得非常混乱,如果你这样做,你更有可能在你的矩阵中访问错误的索引,所以我不建议它。

答案 4 :(得分:0)

你可以做*(*(matrix+i)+j)。它应该等同于括号表示法。这两种符号的作用只是指针算术