gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:31:49 24 4
gpt4 key购买 nike

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

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

关于c++ - C++中的多维数组代码出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28783373/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com