gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:38:44 26 4
gpt4 key购买 nike

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

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

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