铸造一架C结构到另一个 [英] Casting one C structure into another
问题描述
我有两个相同(但命名不同)C的结构:
I have two identical (but differently named) C structures:
typedef struct {
double x;
double y;
double z;
} CMAcceleration;
typedef struct {
double x;
double y;
double z;
} Vector3d;
现在我想将CMAcceleration变量分配给一个变量的Vector3D(复制整个结构)。我怎样才能做到这一点?
Now I want to assign a CMAcceleration variable to a Vector3d variable (copying the whole struct). How can I do this?
我尝试以下,但获得这些编译器错误:
I tried the following but get these compiler errors:
vector = acceleration; // "incompatible type"
vector = (Vector3d)acceleration; // "conversion to non-scalar type requested"
当然,我可以诉诸单独设置所有成员:
Of course I can resort to set all members individually:
vector.x = acceleration.x;
vector.y = acceleration.y;
vector.z = acceleration.z;
但似乎相当不方便。
but that seems rather inconvenient.
什么是最好的解决方案?
What's the best solution?
推荐答案
这(从包成一个功能除外)是你唯一的解决办法:
That's your only solution (apart from wrapping it into a function):
vector.x = acceleration.x;
vector.y = acceleration.y;
vector.z = acceleration.z;
其实你可以施放它,像这样(使用指针)
You could actually cast it, like this (using pointers)
Vector3d *vector = (Vector3d*) &acceleration;
但是这是不是在规格,因此行为取决于编译器,运行和大型绿地的怪物。
but this is not in the specs and therefore the behaviour depends on the compiler, runtime and the big green space monster.
这篇关于铸造一架C结构到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!