C Library Function - memcpy()
C Standard Library - <string.h>
Description
The C library function void *memcpy(void *str1, const void *str2, size_t n) copies n bytes from memory area str2 to memory area str1.
Declaration
Here is the declaration for the memcpy() function.
void *memcpy(void *str1, const void *str2, size_t n)
Parameters
str1 -- A pointer to the destination array where the content is to be copied, type-casted to a void* pointer.
str2 -- A pointer to the source of data to be copied, type-casted to a void* pointer.
n -- The number of bytes to be copied.
Return Value
This function returns a pointer to the destination, which is str1.
Example
The following example demonstrates the use of the memcpy() function.
// Copying a string into an array dest
#include <stdio.h>
#include <string.h>
int main ()
{
const char src[50] = "http://www.tutorialpro.org";
char dest[50];
memcpy(dest, src, strlen(src)+1);
printf("dest = %s\n", dest);
return(0);
}
Let's compile and run the above program, this will produce the following result:
dest = http://www.tutorialpro.org
Copying 6 consecutive characters starting from the 11th character in s to d:
#include <stdio.h>
#include<string.h>
int main()
{
char *s="http://www.tutorialpro.org";
char d[20];
memcpy(d, s+11, 6); // Copying starting from the 11th character (r), 6 consecutive characters (tutorialpro)
// Or memcpy(d, s+11*sizeof(char), 6*sizeof(char));
d[6]='\0';
printf("%s", d);
return 0;
}
Let's compile and run the above program, this will produce the following result:
tutorialpro
Overwriting existing data:
#include<stdio.h>
#include<string.h>
int main(void)
{
char src[] = "***";
char dest[] = "abcdefg";
printf("Before memcpy: %s\n", dest);
memcpy(dest, src, strlen(src));
printf("After memcpy: %s\n", dest);
return 0;
}
Let's compile and run the above program, this will produce the following result:
Before memcpy: abcdefg
After memcpy: ***defg