gpt4 book ai didi

将非 -`void` 指针转换为 `uintptr_t`,反之亦然

转载 作者:太空狗 更新时间:2023-10-29 16:38:35 27 4
gpt4 key购买 nike

有两个相关的C标准规则:

C99 标准,6.3.2.3:

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

7.20.1.4:

The following type designates an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer: uintptr_t

这意味着,以下代码是合规的:

int *p = NULL;
void *q = (void*)p;
uintptr_t s = (uintptr_t)q;

但它真的需要两步转换吗?如果执行以下操作,编译器是否会执行隐式中间转换:

int *p = NULL;
uintptr_t s = (uintptr_t)p;

(好吧,它可能适用于大多数编译器,但我的问题是关于标准合规性)

最佳答案

我不会冒险。该标准非常清楚什么是允许的,什么是不允许的。

编写 uintptr_t s = (uintptr_t)(void*)p; 向您代码的读者发出您知道自己在做什么的信号。

关于将非 -`void` 指针转换为 `uintptr_t`,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34291377/

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