c - 为什么当 N 越界时 &a[N] 不调用 UB?

标签 c arrays pointers undefined-behavior

我在很多例子中看到它是这样写的:

 #define N 5
 ....

 int a[N], *p;
 ....

 for (p = &a[0]; p < &a[N]; p++);

很明显 a[N] 不存在,那么为什么编译器不给出任何警告(如越界)或错误或者它调用 UB?

最佳答案

&a[N] 处的内存永远不会被您的程序访问,所以没问题。 C 标准允许比较数组对象内或数组对象末尾的指针。

编辑以下讨论:

&a[N] 不会导致未定义的行为 - 它完全等同于 a + N。来自 C 标准,6.5.3.2 地址和间接运算符,第 3 段:

The unary & operator yields the address of its operand … if the operand is the result of a [] operator, neither the & operator nor the unary * that is implied by the [] is evaluated and the result is as if the & operator were removed and the [] operator were changed to a + operator.

关于c - 为什么当 N 越界时 &a[N] 不调用 UB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18024849/

相关文章:

javascript - 为什么我的函数不将 json 文件转换为数组 json

JavaScript .split

javascript - 如何存储多连接航点

c - 使用 sizeof 作为指向 2 个 float 数组的指针

c++ - 如何删除树中的节点?

c - 嵌入式系统中的启动代码流程,引导加载程序的概念?

c - C 中的 MPI_Scatter 结构

c - 使用 C 动态存储文件中的信息

c - 输入缓冲区中的最后一个字符 (C)

c - OS X 上的弱符号别名类似于 Linux 上的弱符号别名,还是最接近的等价物?