C library functions -memcpy()

C Standard Library - <string.h>

Description

C Library Functionsvoid *memcpy(void *str1, const void *str2, size_t n)From memory areastr2Copynbytes to storage areastr1。

Declaration

Below is the declaration of the memcpy() function.

void *memcpy(void *str1, const void *str2, size_t n)

Parameter

  • str1Pointer to the destination array used to store the copied content, type-cast to a void* pointer.
  • str2Pointer to the source of data to be copied, type-cast to a void* pointer.
  • n-- the number of bytes to be copied.

Return Value

This function returns a pointer to the destination storage area str1.

Example

The following example demonstrates the usage of the memcpy() function.

Example

// Copy the string into array dest #include <stdio.h> #include <string.h> int main () { const char src[50] = "http://www.example.com"; char dest[50]; memcpy(dest, src, strlen(src)+1); printf("dest = %s\n", dest); return(0); }

Let us compile and run the above program, which will produce the following result:

dest = http://www.example.com

Copy 6 consecutive characters starting from the 11th character in s to d:

Example

#include <stdio.h> #include<string.h> int main() { char *s="http://www.example.com"; char d[20]; memcpy(d, s+11, 6);// Copy starting from the 11th character (r), and copy 6 consecutive characters (example) // Or memcpy(d, s+11*sizeof(char), 6*sizeof(char)); d[6]='\0'; printf("%s", d); return 0; }

Let us compile and run the above program, which will produce the following result:

example

Overwriting part of the original data:

Example

#include<stdio.h> #include<string.h> int main(void) { char src[] = "***"; char dest[] = "abcdefg"; printf("Before using memcpy: %s\n", dest); memcpy(dest, src, strlen(src)); printf("After using memcpy: %s\n", dest); return 0; }

Let us compile and run the above program, which will produce the following result:

使用 memcpy 前: abcdefg
使用 memcpy 后: ***defg

C Standard Library - <string.h>

other extensions