Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between memcpy and '=' when copying simple struct [duplicate]

Tags:

c++

c

struct

memcpy

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 '='?

like image 516
A Lan Avatar asked Aug 31 '26 13:08

A Lan


1 Answers

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.

like image 137
Barmar Avatar answered Sep 02 '26 04:09

Barmar