c - 将 uint32 数字类型转换为结构指针?

标签 c

在使用 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/

相关文章:

c - gcc: fatal error : regex.h: 没有那个文件或目录

c - 关于声明的螺旋法则——什么时候出错了?

c - 打印到 stderr 时检查 fprintf 时出错

c - C中的指针数组实现

将十六进制值转换为字符串

c - 过滤一个缓冲区并将其复制到另一个 C

c - 了解包含大量数字的链表

C结构,指针

c - 为 C 打印扩展 ASCII 字符的好方法是什么?

c - 如何强制我的代码普遍出现段错误?