是否可以取消引用与有效指针比较相等的元素指针?

Can a one past the element pointer that compares equal to a valid pointer be dereferenced?

在 C18 中我们有:

§ 6.5.9p10

Two pointers compare equal if and only if both are null pointers, both are pointers to the same object(including a pointer to an object and a subobject at its beginning) or function, both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space.

因此 int a[4][2] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}, 我们可以 a[1] == a[0] + 2.

结果能保证*(a[1]) == *(a[0] + 2)吗?

不允许取消引用这样的指针,即使它比较等于另一个有效指针。

关于 + 运算符的第 6.5.6p8 节指出:

When an expression that has integer 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 integer 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. If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated

在相关说明中,一些编译器具有指针出处 的概念,这意味着它在内部跟踪指针的来源。这样做的结果是,如果两个不相关的变量在内存中相邻,则将其中一个的地址与另一个的地址进行比较将始终计算为 false,即使地址相同。