我在很多例子中看到它是这样写的:
#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/