无法更改指针矩阵的值

Failing to change values of a pointer matrix

本文关键字:指针      更新时间:2023-10-16

我在使用指针动态更改矩阵值时遇到问题。

我有这些全球声明:

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.

请在这里伸出援助之手,指出我在这里做错了什么。提前感谢!

您收到该错误的原因是您将矩阵作为"按值传递"而不是按"引用"传递,因此请将您的代码替换为此

void TakeInput(float** &matrix, int row, int col)

行和列也应该是整数。

很简单,你按值将matrixP传递给TakeInput,即你在TakeInput中编辑它的副本。请改为执行此操作。

void TakeInput(float*** matrix, float row, float col) {
//use (*matrix) instead
//...
}

TakeInput(&matrixP, row, col);

http://www.learncpp.com/cpp-tutorial/72-passing-arguments-by-value/

指针与通常的整数没有什么不同。

编辑:

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];
    }
}