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 ?
memcpy is usually naive - certainly not the slowest way to copy memory around, but usually quite easy to beat with some loop unrolling, and you can go even further with assembler.
memmove() is similar to memcpy() as it also copies data from a source to destination.
The function memcpy() is used to copy a memory block from one location to another. One is source and another is destination pointed by the pointer. This is declared in “string.
memcpy() is specifically designed to copy areas of memory from one place to another so it should be as efficient as the underlying architecture will allow.
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 =
.
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