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 ?
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 ?
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 =
.
I'm not sure of the performance difference, although I would guess most compilers would use memcpy under the hood.
I would prefer the assignment in most cases, it is much easier to read and is much more explicit as to what the purpose is. Imagine you changed the type of either of the structs, the compiler would guide you to what changes were needed, either giving a compiler error or by using an operator= (if one exists). Whereas the second one would blindly do the copy with the possibility of causing a subtle bug.
Check out this conversation about the very same topic: http://bytes.com/topic/c/answers/670947-struct-assignment
Basically, there are a lot of disagreements about the corner cases in that thread on what the struct copy would do. It's pretty clear if all the members of a struct are simple values (int, double, etc.). The confusion comes in with what happens with arrays and pointers, and padding bytes.
Everything should be pretty clear as to what happens with the memcpy
, as that is a verbatim copy of every byte. This includes both absolute memory pointers, relative offsets, etc.
There is no inherent reason why one would be better in performance than the other. Different compilers, and versions of them, may differ, so if you really care, you profile and benchmark and use facts as a basis to decide.
A straight assignment is clearer to read.
Assignment is a teeny bit riskier to get wrong, so that you assign pointers to structs rather than the structs pointed to. If you fear this, you'll make sure your unit tests cover this. I would not care about this risk. (Similarly, memcpy
is risky because you might get the struct size wrong.)
memcpy
if you use sizeof
and the correct struct. I suppose you could get the struct wrong and there would be no error. I think you'd probably get a segmentation fault eventually though.
Commented
Mar 21, 2011 at 17:05