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

标签 c pointers dereference pointer-arithmetic

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

#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/

相关文章:

c++ - 复制或 constref 一个 shared_ptr?

c - 我将如何迁移到 C 中的新进程?

c - 总是出现段错误

c - 为什么 container_of 不在 glibc 中?

c - 在 C 中释放一棵树

objective-c - 将指针分配给另一个指针会崩溃

C++ vector 问题;通过引用传递东西

c++ - Vector::push_back() 给出读取访问冲突

C 堆栈实现。关于解引用和双指针的问题

c++ - 表达式 : String iterator not dereferencable