Reputation: 61
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
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
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