【问题标题】:Memory issues with two dimensional array二维数组的内存问题
【发布时间】:2011-03-18 20:55:50
【问题描述】:

在我发现this nice example 之后,我试图创建一个函数来动态生成int 值的二维网格(二维数组)。

在您更改值的前几次,它工作得相当好,但如果在那之后崩溃。我猜想释放内存的部分不能正常工作。

void testApp::generate2DGrid() {
    int i, j = 0;

    // Delete previous 2D array
    // (happens when previous value for cols and rows is 0)
    if((numRowsPrev != 0) && (numColumnsPrev != 0)) {
        for (i = 0; i < numRowsPrev; i++) {
            delete [ ] Arr2D[i];
        }
    }

    // Create a 2D array
    Arr2D = new int * [numColumns];
    for (i = 0; i < numColumns; i++) {
        Arr2D[i] = new int[numRows];
    }

    // Assign a random values
    for (i=0; i<numRows; i++) {
        for (j = 0; j < numColumns; j++) {
            Arr2D[i][j] = ofRandom(0, 10);
        }
    }

    // Update previous value with new one
    numRowsPrev = numRows;
    numColumnsPrev = numColumns;
}

【问题讨论】:

    标签: c++ memory arrays multidimensional-array 2d


    【解决方案1】:

    我发现 1 个主要错误:

    // Assign a random values
    for (i=0; i<numRows; i++){
        for (j=0; j<numColumns; j++){
            Arr2D[i][j] = ofRandom(0, 10);
        }
    }
    

    这里变量“i”用作“Arr2D”的第一个索引,最大值为 (numRows -1)
    在这段代码中:

    for (i=0; i<numColumns; i++)
    {
        Arr2D[i] = new int[numRows];
    }
    

    变量“i”用作第一个索引,但最大值为 (numColumns-1)。如果 numRows 比 numColumns 大得多,那么我们就会遇到问题。

    作为旁注。当您尝试清理时,您正在泄漏列:

    if((numRowsPrev != 0) && (numColumnsPrev != 0))
    {
        for (i=0; i<numRowsPrev; i++){
            delete [ ] Arr2D[i];
        }
        // Need to add this line:
        delete [] Arr2D;
    }
    

    接下来要注意的事情。
    这确实不是一个好主意。使用一些提供的 STL 类(或可能提升矩阵)。这看起来像是在绑定全局变量和各种其他讨厌的东西。

    【讨论】:

    • 非常感谢。我会给出另一个有效的答案,因为它看起来是最好的解决方案,但我希望我能在你花时间找出问题所在时同时勾选这两个答案。
    【解决方案2】:

    没有内存问题的 C++ 二维数组:

    #include <vector>
    
    typedef std::vector<int> Array;
    typedef std::vector<Array> TwoDArray;
    

    用法:

    TwoDArray Arr2D; 
    
    // Add rows
    for (int i = 0; i < numRows; ++i) {
        Arr2D.push_back(Array());
    }
    
    // Fill in test data
    for (int i = 0; i < numRows; i++) {    
        for (int j = 0; j < numCols; j++) {
            Arr2D[i].push_back(ofRandom(0, 10));           
        }
    }
    
    // Make sure the data is there
    for (int i = 0; i < numRows; i++) {    
        for (int j = 0; j < numCols; j++) {
            std::cout << Arr2D[i][j] << ' ';
        }
    std::cout << '\n';
    }
    

    【讨论】:

    • 您使用的是 C++ 而不是 C 使用标准库,它可以帮助您避免遇到问题。
    • 快速评论。 // 确保数据存在之后,您应该用 numRows 替换 5,用 numCols 替换 10
    猜你喜欢
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 2019-08-08
    • 2011-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多