The memcpy function is used to copy a block of data from a source address to a destination address. Below is it's prototype.
void * memcpy(void * destination, const void * source, size_t num);
/* A C program to demonstrate working of memcpy */
#include
#include
int main ()
{
char str1[] = "Rahul Kumar";
char str2[] = "Arayan Singh";
puts("str1 before memcpy ");
puts(str1);
void *mymemcpy(void *dest,const void *src,size_t n){
char *vdest = (char *)dest;
char *vsrc = (char *)src;
int i;
for(i = 0; i < n; i++){
vdest[i] = vsrc[i];
}
vdest[i] = '\0';
return vdest;
}
/* Copies contents of str2 to sr1 */
// memcpy (str1, str2, sizeof(str2)-1);
mymemcpy(str1, str2, sizeof(str2));
puts("\nstr1 after memcpy ");
puts(str1);
return 0;
}
The idea is to simply typecast given addresses to char *(char takes 1 byte). Then one by one copy data from source to destination. Below is an implementation of this idea.
1) memcpy() doesn’t check for overflow or \0
2) memcpy() leads to problems when a source and destination addresses overlap.
2) memcpy() leads to problems when a source and destination addresses overlap.
memmove() is another library function that handles overlapping well.
Comments
Post a Comment