本文介绍了C-比较来自不同分配的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我在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:比较指向不相关对象的指针是否相等或不相等,没有未定义的行为.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:这意味着将指针与> ,> = ,< 或< = 当指针没有指向相同的对象时(对于引号中详细描述的相同对象"的定义),行为是不确定的.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-比较来自不同分配的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-05 09:04