c++ - 无法更改指针矩阵的值

标签 c++ pointers matrix

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

我有这些全局声明:

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/

相关文章:

c++ - 这个声明作为英文句子的确切含义是什么?

c - 如何在实模式下使用 C 字符数组

r - 从方阵中删除总和为零的列以及相应的行

c++ - C++中的按位设置

c - NULL、 '\0' 和 0 有什么区别?

r - 计算矩阵的特征值多少钱?

c# - 如何计算WPF中从一个区域/矩形到另一个区域/矩形的变换矩阵?

c++ - 关闭 fstream 是否保证文件系统同步?

c++ - 当使用复制构造函数为持有它的变量分配一个新对象时,前一个对象是否被销毁?

c++ - 在 pcre++ 中命名捕获的子串