将结构的一部分加载到另一个结构中

时间:2014-10-07 12:23:06

标签: c struct

我想将一个带有3个值的结构加载到只有2个值的结构中。

typedef struct {
     double x;
     double y;
     } twod;

typedef struct {
     double x;
     double y;
     double z;
    } threed;

第二个结构包含三维平面的坐标数组。目标是只将xy坐标加载到第二个结构的第一个结构中。

考虑到它们是不同的typedef,这可能吗?如何实施解决方案?

4 个答案:

答案 0 :(得分:1)

不,当然,由于它不合适,所以它不可能直接实现。

但是你可以手动复制字段:

twod atwod;
threed athreed;

athreed.x = 1.0;
athreed.y = 2.0;
athreed.z = 3.0;

atwod.x = athreed.x;
atwod.y = athreed.y;

你可以做出可怕的假设并使用memcpy(),但它不值得。

当然,您也可以使用所有基于继承的内容并重新构建threed

typedef struct {
  twod xy;
  double z;
} threed;

然后你可以这样做:

atwod = athree3.xy;

但对threed的访问变得不那么明确了。

答案 1 :(得分:0)

您只需使用=运算符

即可
threed a = {1.0, 2.0, 3.0};
twod   b;

b.x = a.x;
b.y = a.y;

答案 2 :(得分:0)

持续不断的想法:

typedef struct {
  double x; 
  double y;
} twod;

typedef struct {
  union {
    struct {
      double x;
      double y;
    };
    twod xy;
  };
  double z;
} threed;

示例程序:

int main() {
  threed vec = {1, 2, 3};
  vec.y = 5;
  twod v2 = vec.xy;
  printf("x:%g y:%g z:%g\n", v2.x, v2.y, vec.z);
}

答案 3 :(得分:-1)

我相信这应该有用......

threed from;
from.x = 10;
from.y = 20;
from.z = 30;

twod to;

memcpy(&to, &from, sizeof(double) * 2);
相关问题