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

Cas*_*per 1 c++ multidimensional-array dynamic-memory-allocation

我最近发布了一个关于此的问题,但这是一个不同的问题.我使用动态内存分配创建了一个2D数组,在使用矩阵之后,我们需要通过删除来释放内存,我不明白为什么我们不能用delete [] matrix它来删除它而不是下面代码中的方法

int **matrix;

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

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

因为问题是因为在main()我创建了一个2D数组并使用其他int **函数分配值,我不知道如何删除分配的内存,循环将导致运行时错误

    int main()
    {
        int **matrixA = 0, **matrixB = 0, **matrixResult = 0; // dynamically allocate an array
        int rowA, colA, rowB, colB; // to hold the sizes of the matrices

        // get values for input method
        int inputMethod = userChoiceOfInput();
        if (inputMethod == 1) // select input by keyboard
        {
            cout << "Matrix A inputting...\n";
            matrixA = getMatricesByKeyboard(&rowA, &colA);
            cout << "Matrix B inputting...\n";
            matrixB = getMatricesByKeyboard(&rowB, &colB);
        }
        else if (inputMethod == 2) // select input by files
        {
            matrixA = getMatricesByFileInput("F:\\matrixA.txt", &rowA, &colA); 
            matrixB = getMatricesByFileInput("F:\\matrixB.txt", &rowB, &colB); 
        }

        //addition(matrixA, &rowA, &colA, matrixB, &rowB, &colB);

        cout << matrixA[1][0];  

////////////////////////run time error///////////////////////
    // free allocated memory of matrix A
    for( int i = 0 ; i < rowA ; i++ )
    {
        delete [] matrixA[i] ;
        delete [] matrixA ;
    }
    // free allocated memory of matrix B
    for( int i = 0 ; i < rowB ; i++ )
    {
        delete [] matrixB[i] ;
        delete [] matrixB ;
    }
////////////////////////run time error///////////////////////

        // free allocated memory of matrix A
        delete [] matrixA ; // i dont know what would these delete
        delete [] matrixB ; 

        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

Ton*_*ion 8

您必须浏览矩阵并删除每个数组.在这样做结束时,您可以删除矩阵本身

// free dynamically allocated memory
for( int i = 0 ; i < *row ; i++ )
{
    delete[] matrix[i]; // delete array within matrix
}
// delete actual matrix
delete[] matrix;
Run Code Online (Sandbox Code Playgroud)