我在使用指针动态更改矩阵值时遇到问题。
我有这些全局声明:
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;
}
}
然后我有主要功能我正在接受输入并只是试图显示 matrixP :
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.
请在这里需要帮助,指出我在这里做错了什么。 提前致谢!
最佳答案
您收到该错误的原因是您将矩阵传递为 “按值传递”而不是按“引用”传递,所以用这个替换你的代码
void TakeInput(float** &matrix, int row, int col)
行和列也应该是整数。
关于c++ - 无法更改指针矩阵的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42919337/