ram surada
ram surada

Reputation: 61

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?

Upvotes: 2

Views: 222

Answers (2)

Dipanjan
Dipanjan

Reputation: 301

You can do a memcpy or memmove:

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

Upvotes: 0

too honest for this site
too honest for this site

Reputation: 12263

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).

Upvotes: 4

Related Questions