繁体   English   中英

有人可以向我解释为什么这段代码没有 output 任何东西

[英]Can someone explain to me why this code doesn't output anything

我已经为这里出了什么问题而崩溃了。 在 output 中,我几乎什么也没得到。 很奇怪,通过正常的cout没有什么是 output 。

请帮帮我。 谢谢你。

int main() {
    int x = 111111;
    array<int, 10> numbers;
    numbers.fill(8);
    const auto numbers_copy = numbers;
    int y = 222222;
    
    for (int* i = &y; i <= &x; i++) {
        cout << *i << ' ';
    }
    cout << endl;
}

这个循环:

for (int* i = &y; i <= &x; i++) {

具有未定义的行为 (UB)

比较指向不相关对象的指针有未指定的结果。 在这种情况下, i指向 2 个不同的int对象, xy ,因此第一次比较可能为真也可能不为真,因为无法保证堆栈上的 2 个对象将一个接一个地连续放置在 memory 中,或者以任何特定顺序。

这同样适用于循环的第二次迭代。 在第二次迭代中,当您第二次执行i++时,这是未定义的行为,因为当i指向int时您不能递增那么多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM