C - 比较来自不同分配的指针?

C - Compare Pointers From Different Allocations?

我用C实现了一个AVL树,后来才知道指针比较只在同一个数组中的对象之间有效。在我的实现中,我进行了某些相等性测试。例如,要测试一个节点是否是父节点的右子节点,我可能会测试 node==node->parent->right。但是,节点是根据需要分配的,而不是在连续的块中。这种行为是否已定义?如果不是,您将如何编写此代码?

对于等式和不等式,在标准 (ISO/IEC 9899:2011) §6.5.9 等式运算符 ¶6 中说:

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.

在比较指向不相关对象的指针是否相等时没有未定义的行为。

相比之下,§6.5.8 关系运算符¶5 说:

When two pointers are compared, the result depends on the relative locations in the address space of the objects pointed to. If two pointers to object types both point to the same object, or both point one past the last element of the same array object, they compare equal. If the objects pointed to are members of the same aggregate object, pointers to structure members declared later compare greater than pointers to members declared earlier in the structure, and pointers to array elements with larger subscript values compare greater than pointers to elements of the same array with lower subscript values. All pointers to members of the same union object compare equal. If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P. In all other cases, the behavior is undefined.

这意味着当指针不指向同一对象时,将指针与 >>=<<= 进行比较(对于 'same object' 在引用中详细给出),行为未定义。