When copying a known structure in memory, do you prefer to use memcpy or dereference? What for? In particular, in the following code:
#include <stdio.h>
#include <string.h>
typedef struct {
int foo;
int bar;
} compound;
void copy_using_memcpy (compound * pto, compound * pfrom)
{
memcpy (pto, pfrom, sizeof (compound));
}
void copy_using_deref (compound * pto, compound * pfrom)
{
* pto = * pfrom;
}
int main (int argc, const char * argv [])
{
compound a = {1, 2};
compound b = {0};
compound * pa = & a;
compound * pb = & b;
// method 1
copy_using_memcpy (pb, pa);
// method 2
copy_using_deref (pb, pa);
printf ("% d% d \ n", b.foo, b.bar);
return 0;
}
Do you prefer method 1 or method 2? I looked at the assembly generated by gcc, and it seems that method 2 uses fewer instructions than method 1. Is this assumed that method 2 is preferable in this case? Thanks.
c memory dereference memcpy
Shao-chuan wang
source share