gpt4 book ai didi

c - 为什么允许从 int 转换为 void *?

转载 作者:行者123 更新时间:2023-12-01 22:30:24 25 4
gpt4 key购买 nike

为什么在 C 中允许从 void* 转换为 int,反之亦然?除了 pthread 之外,它还用在什么地方?

最佳答案

这是允许的,但行为是实现定义的。

有时,在某些情况下(在特定平台/体系结构上),此规定可能对于使用运算符涉及内存地址的快速和肮脏 hacks/tricks 有用需要 int 操作数。 [例如:XOR 操作]。可用于内存有限的嵌入式设备的内存优化。

引用有关功能的标准,

The mapping functions for converting a pointer to an integer or an integer to a pointer are intended to be consistent with the addressing structure of the execution environment.

相关阅读:来自c11,第6.3.2.3章,

第 5 段:

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.

和第 6 段:

Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.

关于c - 为什么允许从 int 转换为 void *?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29816434/

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