【问题标题】:C++ Matrix with Arrays and Pointers带有数组和指针的 C++ 矩阵
【发布时间】:2014-10-31 11:42:00
【问题描述】:

我有一个从文件加载矩阵的函数。现在我在将元素存储在正确的位置时遇到了问题。

这是我用于存储矩阵的重要代码。此代码无法更改,因此我必须按原样使用此部分:

int **matrix
*matrix = new int[*rows * *columns];

现在我有一个 while 循环,它正在读取包含矩阵元素的文本文件。

但是如何将值存储在数组的正确位置?

通常我会在while循环中做这样的事情。

matrix[currentRow][currentColumn] = value;

但这在这里不起作用,因为这不是二维数组。

【问题讨论】:

  • 立即解除对未初始化指针的引用绝不是一个好主意。

标签: c++ arrays pointers matrix


【解决方案1】:

您需要将二维索引转换为一维索引。

int currentIndex = (currentRow * nColumns) + currentColumn;
matrix[currentIndex] = X; //actually (*matrix)[currentIndex] given your definition of matrix

【讨论】:

    猜你喜欢
    • 2011-12-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 2017-04-05
    相关资源
    最近更新 更多