简体   繁体   English

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

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

I've already broken my head over what's wrong here.我已经为这里出了什么问题而崩溃了。 In the output I literally get nothing.在 output 中,我几乎什么也没得到。 It is very strange that nothing is output through a normal cout .很奇怪,通过正常的cout没有什么是 output 。

Help me please.请帮帮我。 Thank you.谢谢你。

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;
}

This loop:这个循环:

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

has undefined behavior (UB) .具有未定义的行为 (UB)

Comparing pointers to unrelated objects has unspecified results.比较指向不相关对象的指针有未指定的结果。 In this case i is pointing to 2 different int objects, x and y , so the first comparison may or may not be true, because there is no guarantee that 2 objects on the stack will be placed one after the other contiguously in memory, or in any particular order.在这种情况下, i指向 2 个不同的int对象, xy ,因此第一次比较可能为真也可能不为真,因为无法保证堆栈上的 2 个对象将一个接一个地连续放置在 memory 中,或者以任何特定顺序。

The same applies to the second iteration of the loop.这同样适用于循环的第二次迭代。 In the second iteration, when you do i++ for the second time, this is undefined behavior, since you can't increment i that far when it points to an int .在第二次迭代中,当您第二次执行i++时,这是未定义的行为,因为当i指向int时您不能递增那么多。

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

相关问题 有人可以解释一下为什么 output, C++ 递归 function - Can someone explain me why is that the output, C++ recursive function 有人可以解释我,为什么我的代码不起作用吗? - Can someone explain me, why my code is not working? 有人可以告诉我为什么此代码不打印任何内容吗? - Can someone please tell me why this code doesnt print anything? 有人可以解释为什么我的 Getter Function 不调用吗? - Can Someone Explain Why My Getter Function Doesn't Call? 有人可以向我解释这段代码的作用吗? - Can someone explain to me what this code does? 奇怪的代码...有人可以向我解释一下 - Strange code… Can someone explain me this 有人可以向我解释为什么我的字符串没有在 output 中显示它经常发生在我身上,这是一个简单的例子, - can someone explain to me why my string is not not showing in output it happens to me a lot and this is a simple example, 有人可以向我解释为什么这是我的输出吗? 以及我将如何纠正我的输出? - Can someone explain to me why my output is this? And how would I correct my output? 有人可以向我解释为什么在LLVM的以下代码中使用相同的操作数进行不等式测试? - Can someone explain to me why there is an inequality test with the same operands in the following code from LLVM? 有人可以向我解释这个 makefile 吗? - Can someone explain this makefile to me?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM