【发布时间】:2017-03-21 05:50:29
【问题描述】:
我在使用指针动态更改矩阵值时遇到问题。
我有这些全局声明:
int row, col = 0;
float** matrixP;
float** matrixT;
float** matrixP_;
然后我有一个函数可以从用户那里获取输入以填充 我想要的任何矩阵:
void TakeInput(float** matrix, float row, float col) {
// Initializing the number of rows for the matrix
matrix = new float*[row];
// Initializing the number of columns in a row for the matrix
for (int index = 0; index < row; ++index)
matrix[index] = new float[col];
// Populate the matrix with data
for (int rowIndex = 0; rowIndex < row; rowIndex++) {
for (int colIndex = 0; colIndex < col; colIndex++) {
cout << "Enter the" << rowIndex + 1 << "*" << colIndex + 1 << "entry";
cin >> matrix[rowIndex][colIndex];
}
}
// Showing the matrix data
for (int rowIndex = 0; rowIndex < row; rowIndex++) {
for (int colIndex = 0; colIndex < col; colIndex++) {
cout << matrix[rowIndex][colIndex] << "\t";
}
cout << endl;
}
}
然后我有主要功能我正在接受输入并只是试图显示矩阵P:
int main() {
// Take the first point input
cout << "Enter the row and column for your points matrix" << endl;
cout << "Enter the number of rows : "; cin >> row;
cout << "Enter the number of columns : "; cin >> col;
TakeInput(matrixP, row, col);
cout << "=============================================================" << endl;
// =============================================================
for (int rowIndex = 0; rowIndex < row; rowIndex++) {
for (int colIndex = 0; colIndex < col; colIndex++) {
cout << matrixP[rowIndex][colIndex] << "\t";
}
cout << endl;
}
return 0;
}
现在我在这部分遇到了问题:
for (int rowIndex = 0; rowIndex < row; rowIndex++) {
for (int colIndex = 0; colIndex < col; colIndex++) {
cout << matrixP[rowIndex][colIndex] << "\t";
}
cout << endl;
}
我得到了:
// matrixP is throwing access violation error.
请在这里需要帮助来指出我在这里做错了什么。 提前致谢!
【问题讨论】:
-
简化,简化,简化。如果你不能,make a wrapper class to hide the nastiness.
-
伙计们来吧,我不想在这里优化我的代码,我想找出我的混乱代码做错了什么。我可以使用类,我可以使用许多其他方法来简化我的事情,但我在这里从逻辑上找出我做错了什么。
-
此时我什至没有考虑优化。那是奖金。我的观点是创建、管理和传递包含
float **的matrix比裸float **要容易得多。例如,TakeInput变为matrix TakeInput(int row, int col)。所有的指针疯狂都打包在matrix中,您只需要正确处理一次。