gpt4 book ai didi

将指针转换为更大的 int

转载 作者:太空狗 更新时间:2023-10-29 17:01:34 25 4
gpt4 key购买 nike

我有一个指针。在 32 位系统上它是 32 位。在 64 位系统上,它是 64 位。

我有一个 long long integer 字段用作标识符,有时我想在其中使用指针值。 (我从不转换回指针——一旦我将它转换为整数字段,我只比较它是否相等)。

在 32 位和 64 位系统上,这样做似乎是安全的。 (在较大的指针系统上并非如此)。是真的吗?

然后,有没有办法让GCC仅当在安全的平台(目前是所有目标平台)上构建时才发出以下警告?

error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]

最佳答案

根据标准,不能保证指针适合整数类型。实际上,否则,在大多数个人计算机上,存在多个 memory models .您可以看到指针和整数类型的大小并不总是相同(即使在“传统”计算机上也是如此)。

您应该使用来自 C99 的可选类型 intptr_tuintptr_t

C11 (n1570), § 7.20.1.4

The following type designates a signed 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: intptr_t.

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.

这是一个小例子:

#include <stdio.h>
#include <stdint.h>

int n = 42;
int *p = &n;
intptr_t i = (intptr_t)(void *)p;
int *q = (void *)i;

printf("%d\n", *q);

关于将指针转换为更大的 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13288061/

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