我有两个正在使用的结构,它们的定义几乎相同。这些是在我无法修改的头文件中定义的。
typedef struct
{
uint32_t property1;
uint32_t property2;
} CarV1;
typedef struct
{
uint32_t property1;
uint32_t property2;
/* V2 specific properties */
uint32_t property3;
uint32_t property4;
} CarV2;
在我的代码中,我在文件顶部初始化了 V2 结构,以涵盖我的所有基础:
static const carV2 my_car = {
.property1 = value,
.property2 = value,
/* V2 specific properties */
.property3 = value,
.property4 = value
};
稍后,我想检索已初始化的值并将它们复制到结构中,以便通过 void 指针从函数返回。我有时想要汽车的 V2 属性,有时需要 V1。如何在没有重复定义/初始化的情况下安全地 memcpy?我对C相当陌生,我的理解是这很丑陋,跟着我看这段代码的工程师不会批准。什么是干净的方法来做到这一点?
int get_properties(void *returned_car){
int version = get_version();
switch (version){
case V1:
{
CarV1 *car = returned_car;
memcpy(car, &my_car, sizeof(CarV1)); // is this safe? What's a better way?
}
case V2:
{
CarV2 *car = returned_car;
memcpy(car, &my_car, sizeof(CarV2));
}
}
}