我在很多例子中看到它是这样写的:
#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.
我是一名优秀的程序员,十分优秀!