C-比较来自不同分配的指针? [英] C - Compare Pointers From Different Allocations?

查看:77
本文介绍了C-比较来自不同分配的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have implemented an AVL tree in C. Only later did I read that pointer comparison is only valid between objects in the same array. In my implementation, I do certain equality tests. For example, to test whether a node is a right child of a parent I might test node==node->parent->right. However, the nodes are allocated as needed, not in a contiguous chunk. Is this behavior defined? How would you write this code instead if it is not?

推荐答案

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

For equality and inequality, in the standard (ISO/IEC 9899:2011) §6.5.9 Equality Operators ¶6 says:

当且仅当两个都是空指针时,两个指针比较相等,两个都是指向同一个对象的指针(包括指向一个对象和它的开始处的子对象的指针)或函数,两个都是指向最后一个元素的指针相同的数组对象,或者一个是指向一个数组对象末尾的指针,另一个是指向另一个数组对象的起点的指针,而该数组对象恰好紧随地址空间中的第一个数组对象.

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.

比较指向不相关对象的指针是否相等或不相等,没有未​​定义的行为.

There's no undefined behaviour in comparing pointers to unrelated objects for equality or inequality.

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

By contrast, §6.5.8 Relational Operators ¶5 says:

比较两个指针时,结果取决于所指向对象在地址空间中的相对位置.如果两个指向对象类型的指针都指向同一对象,或者都指向同一数组对象的最后一个元素,则它们的比较相等.如果所指向的对象是同一聚合对象的成员,则指向稍后声明的结构成员的指针大于指向早于该结构声明的成员的指针,指向具有较大下标值的数组元素的指针大于指向同一数组的元素的指针下标值较低.指向同一个联合对象的成员的所有指针比较相等.如果表达式P指向数组对象的元素,而表达式Q指向同一数组对象的最后一个元素,则指针表达式Q + 1的比较值大于P.在所有其他情况下,该行为均未定义.

这意味着将指针与> > = < < = 当指针没有指向相同的对象时(对于引号中详细描述的相同对象"的定义),行为是不确定的.

This means that comparing pointers with >, >=, < or <= when the pointers are not pointing to the same object (for the definition of 'same object' given in painstaking detail in the quote), the behaviour is undefined.

这篇关于C-比较来自不同分配的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆