C++中的多维数组代码出错

Error in Multidimensional array code in C++

我最近一直在修改我的编码技巧,然后我做了一个程序,输出一个多维数组的内容。这很简单,但是当我试验代码时,情况就是这样:

int dv[3][3] {
    {1,2,3},
    {4,5,6},
    {7,8,9}
};
for (auto col = dv; col != dv + 3; ++col) {
    for (auto row = *dv; row != *col + 3; ++row) {
        cout << *row << " ";
    }
}

输出:

1 2 3 1 2 3 4 5 6 1 2 3 4 5 6 7 8 9

谁能告诉我为什么会这样?

为什么我的代码输出如此?

您的错误在第二个循环初始化中:auto row = *dv;。通过这样做,您可以系统地回到起点。然后,你去*col + 3。 这样看:

第一次循环:

col = dv;
row = *dv;

Prints each number until row == *col + 3

Output : 1 2 3

第二次循环:

col = dv + 3;
row = *dv;

Prints each number until row == *col + 3 but col is dv + 3

Output : 1 2 3 4 5 6 --> It started from the beginning (dv)

回合 1 和回合 2 的总输出: 1 2 3 1 2 3 4 5 6

试试这个:

for (auto col = dv; col != dv + 3; ++col) {
    for (auto row = *col; row != *col + 3; ++row) { // (1)
        cout << *row << " ";
    }
}

// (1) : Starting at current `column` then printing until `column + 3`

实例 : https://ideone.com/Y0MKrW

您的内部循环从 *dv 开始。那可能不是你想要做的。