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

Cas*_*per 6 c++ dynamic-memory-allocation

几天前,我学会了如何从互联网创建2D分配的内存阵列,它完美无缺.要访问数组我们只是简单地使用matrix[i][j],但是有什么方法可以通过使用*符号而不是[]输入以及其他方法来取消引用这个2D数组?

第一个问题解决了我可以使用 *(*(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 ;
Run Code Online (Sandbox Code Playgroud)

JBL*_*JBL 5

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

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

你实际上分配指针(您的矩阵的变量,它是一个双指针)和整数的"行"阵列(每一个代表在矩阵的一行,大小"栏"),这是一个阵列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 ;
Run Code Online (Sandbox Code Playgroud)

循环中的删除将释放矩阵的每一行,最后的删除将释放行数组.在你的代码中,你row在双指针(matrix)上使用删除时间,这是没有意义的.

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


Pub*_*bby 3

既然a[b]只是*(a + b)你当然可以这样做:

*(*(matrix + i) + j)
Run Code Online (Sandbox Code Playgroud)

无论如何,这些new分配很容易出错。如果其中一个嵌套new的抛出异常,那么就会发生泄漏。尝试使用std::vector替代。