gpt4 book ai didi

c++ - 如果不使用它,访问数组外的数据是否不正确?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:10:15 26 4
gpt4 key购买 nike

在我正在编写的算法中,我可以有以下内容(当然是经过简化的)

int a[3] = {1,2,3};
int b = a[3];

当用于填充b的索引溢出时,我从不使用b的值。代码仍然不正确吗?我是否必须进行明确的边界检查?

最佳答案

无论您是否使用 b,此代码都有未定义的行为。为什么?因为根据定义,a[3] 等同于 *(a+3)。这里引用标准中的一段话,证明 *(a+3) 本身是未定义的,无论该值是被存储、使用还是单独保留。

When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i+n-th and i−n-th elements of the array object, provided they exist. Moreover, if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object. 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.

关于c++ - 如果不使用它,访问数组外的数据是否不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6572923/

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