Tuesday, February 24, 2009

memcpy() vs. memmove() in C

Here is the difference between memcpy() and memmove().

Example:
str = "strings are good";
memmove(str + 8, str + 11, 4);
This returns --> strings are are good
memcpy(str + 8, str + 11, 4);
This returns --> strings are ared

Example:


/* memcpy example */
#include
#include

int main ()
{
char str1[]="Sample string";
char str2[40];
char str3[40];
memcpy (str2,str1,strlen(str1)+1);
memcpy (str3,"copy successful",16);
printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
return 0;
}

Output:
str1: Sample string
str2: Sample string
str3: copy successful

Example:


/* memmove example */
#include
#include

int main ()
{
char str[] = "memmove can be very useful......";
memmove (str+20,str+15,11);
puts (str);
return 0;
}

Output:
memmove can be very very useful.

No comments: