Consider copy a simple struct which doesn't require special copy semantics.
struct A
{
char i
int i;
long l;
double b;
//...maybe more member
}
struct A a;
a.c = 'a'; //skip other member just for illustrate
struct A b;
memset(&a, 0, sizeof(a));
b.c = a.c;
//...for other members, the first way to assign
memcpy(&b, &a, sizeof(b)); //the second way
b = a; //the third way
The 3 methods do the same thing, and it seems all of them are correct. I used to use 'memcpy' for copying simple structs, but seems now '=' can do the same thing. So is there any difference between using memcpy and '='?
memcpy treats the structure as a contiguous array of bytes, and just copies all of them. As a result, it will always copy the padding bytes after members.
= is only required to copy the members. It might or might not copy the padding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With