我需要一个动态的二维数组,它将表示一个标准矩阵。大小和元素在运行时从文件读入。C++在二维数组指针访问值
从其他堆栈的帖子中获取方向我已经设置了我的数组,如下所示;
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);
}
}
}
我应该补充一点,我知道我可以使用矢量。我在这里挑战自己负责任地使用指针构建,使用和释放二维数组。
在单个内存块int * table = new int [size * size];中使用'table [column + size * row]'(或make围绕这个简单的包装类)? – hyde 2013-02-27 18:07:21
可能是。我在这个项目的早些时候正在考虑这个方法。这里的陷阱就是第二个数组。 – frankV 2013-02-27 18:25:20
您的评论似乎被切断了,但您仍然可以使用行指针轻松生成额外的数组:'int * rows []'并且避免每行有堆块的开销。或者只是'int * rowarray = table + row * size'。 – hyde 2013-02-27 18:42:53