将一个 C 结构转换为另一个

编程入门 行业动态 更新时间:2024-10-19 15:41:50
本文介绍了将一个 C 结构转换为另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个相同(但名称不同)的 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;

但这似乎很不方便.

最好的解决方案是什么?

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 结构转换为另一个

本文发布于:2023-11-17 02:09:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608423.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   结构

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!