[英]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
对象, x
和y
,因此第一次比较可能为真也可能不为真,因为无法保证堆栈上的 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.