且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

指针算术在数组之外仍然有效吗?

更新时间:2023-11-29 15:21:46

您所做的工作适用于您正在使用的实现以及最流行的实现,但它不符合 C.正如 chris 所引用的,

What you're doing works on the implementation you're using, as well as most popular implementations, but it's not conforming C. As chris cited,

>

§6.5.6/8:如果指针操作数和结果都指向同一个数组对象的元素,或者数组对象的最后一个元素之后,求值不会产生溢出;否则,行为未定义

§6.5.6/8: 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

未定义的事实在未来可能会变得越来越重要,更高级的静态分析允许编译器将此类代码转换为致命错误,而不会产生运行时成本.

The fact that it's undefined will probably become increasingly important in the future, with more advanced static analysis allowing compilers to turn this kind of code into fatal errors without incurring runtime cost.

顺便说一下,在未定义的同一数组中减去指针的历史原因是分段内存(想想 16 位 x86;熟悉它的人会想到大"内存模型).虽然指针可能涉及段和偏移组件,但编译器可以只对偏移组件进行算术运算,以避免运行时成本.这使得不在同一段中的指针之间的算术无效,因为差异的高位"丢失了.

By the way, the historical reason for subtracting pointers not within the same array being undefined is segmented memory (think 16-bit x86; those familiar with it will want to think of the "large" memory model). While pointers might involve a segment and offset component, a compiler could do the arithmetic just on the offset component to avoid runtime cost. This makes arithmetic between pointers not in the same segment invalid since the "high part" of the difference is lost.