gpt4 book ai didi

c - 相同的源代码,但不同操作系统上的结果不同

转载 作者:行者123 更新时间:2023-11-30 15:13:43 25 4
gpt4 key购买 nike

我正在学习指针。我在教程中看到了这个代码示例。我尝试了一下,但结果与教程不同。

#include <stdio.h>
#include <stdlib.h>

int main()
{
int i = 5;
int myInt = 7;
int *pointer = &i;
printf("%i\n", *(pointer + 1));

return 0;

}
  • 在 Windows 计算机上,输出为 2686740

  • 在 Linux 计算机上,输出为 7。

这是什么原因?

最佳答案

为了详细说明现有答案,我想添加一个解释。

在您的代码中,i 是一个 int 变量。您将i的地址分配给pointer。美好的。然后,您要做的就是增加指针(地址),然后尝试取消引用它。

现在,与代码中的语句相比,

printf("%i\n", *(pointer + 1));    

引用 C11 标准,第 §6.5.6 章,加法运算符

[....] If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.

本质上,通过这样做,您正在尝试访问一些未分配给您的进程的内存,从而调用 undefined behavior .

UB 的输出未定义

关于c - 相同的源代码,但不同操作系统上的结果不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34409096/

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