Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct assignment or memcpy? [duplicate]

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 ?

like image 335
ofaurax Avatar asked Mar 21 '11 13:03

ofaurax


People also ask

Is memcpy inefficient?

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.

What can I use instead of memcpy?

memmove() is similar to memcpy() as it also copies data from a source to destination.

When should memcpy be used?

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.

Why do we use memcpy?

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.


1 Answers

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 =.

like image 188
Alexander Gessler Avatar answered Sep 23 '22 22:09

Alexander Gessler