gpt4 book ai didi

c - 往返转换后指针的相等关系是否保证是可传递的?

转载 作者:行者123 更新时间:2023-12-04 12:17:52 27 4
gpt4 key购买 nike

这个问题类似于“Are all pointers guaranteed to round-trip through void * correctly?”,但更深一些。
鉴于:

#include <stdint.h>
int i;
int *ip1 = &i;
void *vp1 = ip1;
intptr_t x = (intptr_t)vp1;
void *vp2 = (void *)x;
int *ip2 = vp2;
然后 vp1 == vp2保证为真(即使它们可能不共享相同的二进制表示),但是 ip1 == ip2保证是真的?即,在这种情况下,相等关系是可传递的吗?

最佳答案

这种转换保证有效。
首先,从对象指针到 void * 的转换C standard 的第 6.3.2.3p1 节对返回进行了描述。 :

A pointer to void may be converted to or from a pointer to any object type. A pointer toany object type may be converted to a pointer to void and back again; the result shallcompare equal to the original pointer


二、从 void *转换而来到 intptr_t并返回在第 7.20.1.4p1 节中描述:

The following type designates a signed integer type with theproperty that any valid pointer to void can be converted tothis type, then converted back to pointer to void, and theresult will compare equal to the original pointer:

intptr_t

The following type designates an unsigned integer type withthe property that any valid pointer to void can be converted tothis type, then converted back to pointer to void, and theresult will compare equal to the original pointer:

uintptr_t

These types are optional.


在这种情况下,一个 int * ( ip1 ) 转换为 void * ( vp1 ) 和 void *intptr_t . intptr_t被转换回 void * ( vp2 )。由 7.20.1.4p1, vp2必须比较等于 vp1 .
然后 vp2转换为 int * ( ip2 )。自 vp2vp1 相同,转换 vp2int *相当于转换 vp1int *因此将产生一个比较等于 ip1 的指针按照 6.3.2.3p1。

关于c - 往返转换后指针的相等关系是否保证是可传递的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69180325/

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