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

标签 c++ c arrays undefined-behavior

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

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/

相关文章:

python - 从三个一维数组创建一个 3D 坐标的 numpy 数组

arrays - 是否可以使用 gnuplot 以这种格式绘制一系列矩阵

c - 将随机索引选取到排序数组中

c++ - 查找数组中一组数字的起点和终点

c++ - 如何在 3D 空间中生成随机点?

c - 传递函数指针

c - C 中等式前的预期表达式

c++ - 旋转对象及其 'children'

c++ - 如何获取使用标准库创建的线程的 winapi id?

c - 字符串操作中的问题