简体   繁体   English

用浮点数作为成员在C中复制结构

[英]Copying structs in C with floats as members

I have three structure types as shown below... 我有三种结构类型,如下所示...

typedef struct _ABC_
{
  float a;
  float b;
  float c;
}ABC;

typedef struct _XYZ_1_
{
  int a0;
  ABC abc1; 
}XYZ1;

typedef struct _XYZ_2
{
  int a1;
  ABC abc2;
}XYZ2;

I want to copy the struct ABC in the struct XYZ2 to the struct ABC defined as a member in struct XYZ1. 我想将结构XYZ2中的结构ABC复制到定义为结构XYZ1中的成员的结构ABC。

I know the most basic way as: 我知道最基本的方法是:

fn(){
  XYZ2 xyz2;
  XYZ1 xyz1;

  /* …code to initialize… */

  xyz1.abc1.a = xyz2.abc2.a;
  xyz1.abc1.b = xyz2.abc2.c;
  xyz1.abc1.c = xyz2.abc2.c;
}

Is there a more efficient way? 有没有更有效的方法?

The most efficient way (in the sense of short source code, maintainability, extendability, run-time speed, but not necessarily target code-size) would be: 最有效的方法(从短代码,可维护性,可扩展性,运行时速度,但不一定是目标代码大小的意义上来说)将是:

xyz1.abc1 = xyz2.abc2;

Read about struct assignment. 了解有关结构分配的信息。

Note 注意

fn()

is not a valid function declaration. 不是有效的函数声明。 Please use correct prototype-syntax, K&R-style is long time outdated; 请使用正确的原型语法,K&R样式已过时; since C99 your compiler has to warn about it; 从C99开始,您的编译器必须对其进行警告; C11 has announced obsolescence (hopefully in C17). C11已宣布过时(希望在C17中)。

You can do a memcpy or memmove : 您可以执行memcpymemmove

memcpy(&xyz1.abc1, &xyz2.abc2, sizeof(ABC));
memmove(&xyz1.abc1, &xyz2.abc2, sizeof(ABC));

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

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