gpt4 book ai didi

c - 将整数转换为结构的有效性如何

转载 作者:太空宇宙 更新时间:2023-11-04 03:25:17 24 4
gpt4 key购买 nike

我有一段代码,其中将整数转换为结构指针会在 gcc (linux) 上引发警告

typedef struct st {
int a;
char *b;
}st;
...
int handle;

int main() {
...
st *sptr = (st*)handle;
...
}

根据C11规范

An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.

我的问题是 我们可以将整数转换为结构指针,还是我们应该寻找其他方法并将其保留为最后的手段?

最佳答案

有两件事需要考虑:

  • 可能无法表示结果。 int 可能与给定平台的指针类型具有不同的表示形式。这就是为什么 uintptr_t 在这种情况下存在的原因。 uintptr_t handle; 将使您的代码可移植。

  • 整数值必须是可以解释为给定系统的对齐地址的值。

关于c - 将整数转换为结构的有效性如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41691825/

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