gpt4 book ai didi

可以取消引用与有效指针比较的元素指针之后的指针吗?

转载 作者:行者123 更新时间:2023-12-03 21:11:55 25 4
gpt4 key购买 nike

在 C18 中,我们有:

§ 6.5.9p10

Two pointers compare equal if and only if both are null pointers, both arepointers to the same object(including a pointer to an object and a subobjectat its beginning) or function, both are pointers to one past the last elementof the same array object, or one is a pointer to one past the end of onearray object and the other is a pointer to the start of a different arrayobject that happens to immediately follow the first array object in theaddress 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 orsubtracted from a pointer, the result has the type of the pointeroperand. If the pointer operand points to an element of an arrayobject, and the array is large enough, the result points to an elementoffset from the original element such that the difference of thesubscripts of the resulting and original array elements equals theinteger expression. In other words, if the expression P points tothe 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 thearray object, provided they exist. Moreover, if theexpression P points to the last element of an array object, theexpression (P)+1 points one past the last element of the arrayobject, and if the expression Q points one past the lastelement of an array object,the expression (Q)-1 points to thelast element of the array object. If both the pointer operandand the result point to elements of the same array object,or one past the last element of the array object, the evaluationshall 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 isevaluated


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

关于可以取消引用与有效指针比较的元素指针之后的指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63208383/

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