简体   繁体   中英

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.

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; since C99 your compiler has to warn about it; C11 has announced obsolescence (hopefully in C17).

You can do a memcpy or memmove :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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