简体   繁体   English

使用 memcpy 将 int 转换为 union/struct 类型

[英]Using memcpy to cast int to union/struct type

I am new to the programming world.我是编程世界的新手。

int a = 10;
typedef union {
  struct {
    int a1;
    ....
    ...
  }
  unsigned int b1;
} type_union;

type_union *ptr = (type_union *)&a;

This typecast is not conventional it seems.这种类型转换似乎不是传统的。 Can you suggest how can I use memcpy to do the same.你能建议我如何使用 memcpy 来做同样的事情。

OP comments giving a misra 11.3 error . OP 评论给出了 misra 11.3 错误

[MISRA 2012 Rule 11.3, required]: A cast shall not be performed between a pointer to object type and a pointer to a different object type. [MISRA 2012 规则 11.3,必需]:不得在指向 object 类型的指针和指向不同 object 类型的指针之间执行强制转换。

The alignment requirements of an int and union may differ (example: union needs may exceed int ) so... intunion的 alignment 要求可能不同(例如: union需求可能超过int )所以...

type_union *ptr = (type_union *)&a;  // Bad

... risks undefined behavior (UB). ... 有未定义行为(UB) 的风险。

Instead, create an object of type type_union and copy the data.相反,创建 type_union 类型的type_union并复制数据。 memcpy() is not used to cast , but to copy. memcpy()不用于强制转换,而是用于复制。

type_union obj; 
obj.tbd.a1 = a;  // tbd as OP's source lacks a member name,
// or 
memcpy(&obj, &a, sizeof a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM