我正在尝试从如下所示的文本文件中加载数据:

161,77,88,255
0,44,33,11,111

等。我有操纵它的功能,并确保该数组是正确的大小(可能会有所不同)。以下是我的实现尝试:

bool loadData(int **imgPix, string fileName) {

ifstream inputFile;

inputFile.open(fileName.c_str());

string tempLineRow; //The resulting line from the text file
string tempElementColumn; //The individual integer element
int numberOfCols = 0;
int numberOfRows = 0;


if (!inputFile.is_open()) {
    return false;
}

imgPix = new int* [numberOfRows];

    while (getline(inputFile, tempLineRow, '\n')) {

        stringstream ss;
        ss << tempLineRow; //Stringstream version of the line

        while (getline(ss, tempElementColumn, ',' )) {
            stringstream ss2;
            ss2 << tempElementColumn;
            ss2 >> numberOfCols;

//Prob?         (**imgPix) = *(*(imgPix + numberOfRows) + numberOfCols);
            numberOfCols++;

        }

        numberOfRows++;

    }

inputFile.close();
return true;


}

我用注释将双指针分配给了这一行,因为我相信这是我的错误的根源,尽管可能还有其他错误。我不确定如何使用已实现的while循环结构来迭代更新2D数组。

谁能提供帮助?将不胜感激!

最佳答案

imgPix = new int* [numberOfRows]


这里numberOfRows = 0,所以您没有分配足够的内存。在分配内存之前,您需要了解阵列的尺寸。
然后,您还应该为数组中的每一行分配一个内存:

imgPix[currentRow] = new int [TotalCols];


对于二维矩形数组,创建TotalRows * TotalCols元素的一维数组,然后使用公式A(row, col) = A[row*TotalCols + col]对其进行访问将更为有效。

10-04 22:07
查看更多