我需要一个动态的二维整数数组,它将代表一个标准矩阵。大小和元素在运行时从文件中读取。
从其他堆栈帖子中获取指导,我将数组设置如下;
void buildArray(ifstream &file, int** 2dArray);
void buildQueue(Queue<int> &Q, int** 2dArray);
int main()
{
int** 2dArray;
Queue<int> Q;
//...
// open file
//...
buildMatrix(file, 2dArray)
buildQueue(Q, 2dArray)
}
void buildArray(ifstream &file, int** 2dArray)
{
int size, element;
while (file.good()) {
file >> size;
2dArray = new int*[size];
for (int i = 0; i < size; i++)
2dArray[i] = new int[size];
// now I should be able to use 2dArray[r][c]
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
file >> element;
2dArray[i][j] = element;
}
}
}
然后我需要读取存储在每个位置 [r][c] 的整数并建立一个队列。我认为我的问题是取消引用指针......但我不确定。
void buildQueue(Queue<int> &Q, int** 2dArray)
{
int row, column, element;
// size is passed in as well, size is our rows or columns size here
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
row = i;
column = j;
element = 2dArray[i][j]; // getting seg fault here!
Q.push_back(row, column, element);
}
}
}
我应该补充一点,我知道我可以使用向量。我在这里挑战自己,负责任地使用指针构建、使用和取消分配二维数组。