C memcpy() function
C memcpy() function - copy bytes in memory
Syntax:
void *memcpy(void *s1, const void * s2, size_t n)
The memcpy() function is used to copy n bytes from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.
Parameters:
Name | Description | Required /Optional |
---|---|---|
s1 | New buffer. | Required |
s2 | Buffer to copy from. | Required |
n | Number of characters to copy. | Optional |
Return value from memcpy()
The memcpy() function shall return s. No return value is reserved to indicate an error.
Example: memcpy() function.
The following example shows the usage of memcpy() function.
#include <stdio.h>
#include <string.h>
char str1[9] = "AAABBCCD";
int main( void )
{
printf( "Original string: %s\n", str1 );
memcpy( str1 + 3, str1, 5 );
printf( "New string: %s\n", str1 );
}
Output:
Original string: AAABBCCD New string: AAAAAABB
Example that uses memcpy() function
Following example copies the contents of source to target.
#include <string.h>
#include <stdio.h>
#define MAX_LEN 80
char str1[ MAX_LEN ] = "This is the string1";
char str2[ MAX_LEN ] = "This is the string2";
int main(void)
{
printf("Before memcpy, strings are:");
printf("\n%s",str1);
printf("\n%s",str2);
memcpy(str2, str1, sizeof(str1));
printf( "\n\nAfter memcpy, strings are:");
printf("\n%s",str1);
printf("\n%s",str2);
}
Output:
Before memcpy, strings are: This is the string1 This is the string2 After memcpy, strings are: This is the string1 This is the string1
C Programming Code Editor:
Previous C Programming: C memcmp()
Next C Programming: C memmove()
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics