在使用 C 语言时,我遇到了一些将 uint32 数字类型转换为结构指针的代码,我无法评估这是对还是错,你们能帮我解决这个问题吗?
typedef struct
{
uint32 a;
//some other element;
} StructA;
int main()
{
StructA *a;
uint32 b;
b = //assign a value for b;
a = (StructA*)b;
}
这种将 b 强制转换为 StructA 指针的类型正确吗?请向我解释为什么这是对或错,非常感谢您的帮助
最佳答案
这段代码的作用是将整数转换为指针类型。这就是语言对于这种转换的说法:
6.3.2.3 Pointers
...
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.
因此,您必须查找实现的文档(即编译器)以查看是否允许这样做。请注意,此代码不可移植,很可能会导致未定义的行为。
关于c - 将 uint32 数字类型转换为结构指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56217798/