1

我最近发布了一个关于此的问题,但这是一个不同的问题。我使用动态内存分配创建了一个二维数组,使用矩阵后,我们需要通过删除它来释放内存,我不明白为什么我们不能只使用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 ;
    }

因为问题是因为main()我创建了一个二维数组并使用其他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;
    }
4

3 回答 3

13

您必须遍历矩阵并删除每个数组。最后,您可以删除矩阵本身

// free dynamically allocated memory
for( int i = 0 ; i < *row ; i++ )
{
    delete[] matrix[i]; // delete array within matrix
}
// delete actual matrix
delete[] matrix;
于 2013-02-12T09:49:55.500 回答
4

如果您无论如何都在使用动态数组,我强烈建议您使用 std::vector。性能损失几乎没有,考虑到您可以更优雅地使用标准算法和向量,您的代码很可能最终会获得更高的性能。

unsigned int cols=40, rows=35;
std::vector<int> temp(cols,0); //this is only created so that we can initialize a 
                               //row at a time, the first parameter is the amount of 
                               //elements to initialize with and the second is the value
                               //to initialize with
std::vector<std::vector<int>> matrix(rows,temp); //creates a vector with 35 vectors each
                                                 //initialized with the values in temp

matrix[2][3] = 4;              //use just like a normal array
matrix.resize(88,temp);         //you can add rows later too
matrix.push_back(temp);         //or like this

//probably the most important, you don't need to delete because you never needed to 
//use new in the first place

使用 new 和 delete 并不是真正的现代风格,这是有充分理由的。根据 C++ 和 Beyond 约定的专家,它应该只在性能优化和编写库代码时使用。许多书籍和老师仍然以这种方式教学,但另一方面,大多数书籍都是垃圾。以下是其中的精华:The Definitive C++ Book Guide and List

于 2013-02-12T09:53:39.793 回答
0

因为 int* 类型没有析构函数,至少它没有你想要的析构函数。你可以通过做这样的事情来避免所有内存分配/释放的东西

std::vector<int*> matrix(rows);
std::vector<int> allData(rows * cols);
for(int i = 0; i < rows; i++)
{
matrix[i] = &allData[i * cols];
}

或使用标准容器,如 boost::numeric::ublas::matrix。

于 2013-02-12T10:05:48.310 回答