多维数组在cpp中打印错误值

Multidimensional array printing wrong values in cpp

我一直在努力使用一个简单的 class 表示 C++ 中的矩阵。我没有使用多维数组,而是决定使用平面数组并通过 [row * x_dim + col] 计算相应单元格的索引来访问值。我只想使用 2D 矩阵。 理想情况下,我还会创建 getter 和 setter 函数,但由于我已经遇到了麻烦,所以我暂时跳过了它们。 主要问题是,在设置值之后,这些值似乎在某个地方被破坏了,因为当再次打印它们时,我读取的值与我实际存储的值不同。 这是(简化的)header MyMatrix.h:

class MyMatrix{
    public:
        int x_dim, y_dim;

        float *my_matrix;

        MyMatrix(int x, int y);
        ~MyMatrix();
};

这里是MyMatrix.cpp:

#include "MyMatrix.h"

MyMatrix::MyMatrix(int x, int y){
    x_dim = x;
    y_dim = y;

    my_matrix = new float[x * y];
}

MyMatrix::~MyMatrix(){
    delete[] my_matrix;
}

现在,当创建 MyMatrix 的新实例时,用递增的数字填充数组,然后再次打印值,我在(平面)矩阵中的某些单元格中得到了不同的值。这是我所做的:

#include "MyMatrix.h"
#include <iostream>

int main(){

    MyMatrix test(3, 4);

    //filling the array in test with ascending numbers
    for(int row = 0; row < test.x_dim; row++){
        for(int col = 0; col < test.y_dim; col++){
            test.my_matrix[row * test.x_dim + col] = col+1;
        }
    }


    for(int row = 0; row < test.x_dim; row++){
        std::cout << "Row " << row << ": ";
        for(int col = 0; col < test.y_dim; col++){
            std::cout  << test.my_matrix[row * test.x_dim + col] << "  ";
        }
        std::cout << std::endl;
    }
}

所以我的输出应该是这样的:

Row 0: 1  2  3  4  
Row 1: 1  2  3  4  
Row 2: 1  2  3  4 

但是,它看起来像这样:

Row 0: 1  2  3  1  
Row 1: 1  2  3  1  
Row 2: 1  2  3  4 

如您所见,前两行的第 3 列中有 1 而不是 4。 我真的一直在努力确定这里的潜在问题,但我无法弄清楚,所以我将不胜感激! 谢谢!

我在 M1 Pro 和 g++ 编译器上使用 clang 版本 13.0.0。

这是错误的索引:

 row * test.x_dim + col

假设您处于外循环的最后一次迭代中,然后 row == x_dim-1 并且您得到:

 (x_dim-1) * x_dim + col

虽然它应该是(假设 x 是行):

 (y_dim-1) * x_dim + col

提示:您的变量命名 col vs x_dimrow vs y_dim 可以做得更好。 xx_dimyy_dimcolnum_columnsrownum_rows会更少容易出错。