gpt4 book ai didi

C: NULL > NULL 总是假?

转载 作者:行者123 更新时间:2023-12-03 07:50:33 25 4
gpt4 key购买 nike

C 标准是否保证,给定 type_t* x = NULL; type_t* y = NULL;我们总是有x > y评价为假?我问这个是因为 initial or terminal malloc buffer possible? 中的对话由此看来,人们应该小心指针比较,并且只有在处理指向同一数组元素的指针时才进行比较,松散地说。不过有x > y就很方便了保证评估为 false,因为我想要一个结构,它是一个堆栈数组,具有第一个和最后一个元素的字段,并且如果该数组仍然有 0元素,将这些字段设置为 NULL 很方便,并且仍然允许 for 很方便循环遍历数组的元素,而不显式检查数组是否有 0元素或更多,所以这样的比较很方便......

最佳答案

令人惊讶的是,在 C 中它似乎会导致未定义的行为。仅==!=可以使用空指针。解决方法是将指针强制转换为 uintptr_t并比较结果。

C17 6.5.8 Relational operators /5

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

(粗体我的)

这与 C++ 不同,其中有一个子句明确指出 < , <= , > , >=== 一致, != :

[expr#rel]/5

If two operands p and q compare equal ([expr.eq]), p<=q and p>=q both yield true and p<q and p>q both yield false. ...

关于C: NULL > NULL 总是假?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77252508/

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