Struct assignment or memcpy?

ofaurax picture ofaurax · Mar 21, 2011 · Viewed 78.7k times · Source

If I want to replicate a structure in another one (in C), what are the pro&con's of :

struct1 = struct2;

vs

memcpy(&struct1, &struct2, sizeof(mystruct_t));

Are they equivalent ? Is there a difference in performance or memory use ?

Answer

Alexander Gessler picture Alexander Gessler · Mar 21, 2011

The struct1=struct2; notation is not only more concise, but also shorter and leaves more optimization opportunities to the compiler. The semantic meaning of = is an assignment, while memcpy just copies memory. That's a huge difference in readability as well, although memcpy does the same in this case.

Use =.