The Wayback Machine - https://web.archive.org/web/20230912003108/https://www.geeksforgeeks.org/memcpy-in-cc/
Related Articles
Open In App
Related Articles

memcpy() in C/C++

Improve Article
Improve
Save Article
Save
Like Article
Like

memcpy() is used to copy a block of memory from one location to another. It is declared in <string.h> header file.

Syntax of memcpy()

The memcpy() syntax is:

void *memcpy(void *to, const void *from, size_t numBytes);

It copies “numBytes” bytes from address “from” to address “to”.

Parameters

  • to: A pointer to the memory location where the copied data will be stored.
  • from: A pointer to the memory location from where the data is to be copied.
  • num: The number of bytes to be copied.

Return Value

  • It returns a pointer to the memory location where data is copied.

Example of memcpy()

Below is the C program to show the working of memcpy()

C




/* A C program to demonstrate working of memcpy */
#include <stdio.h>
#include <string.h>
 
int main()
{
    char str1[] = "Geeks";
    char str2[] = "Quiz";
 
    puts("str1 before memcpy ");
    puts(str1);
 
    /* Copies contents of str2 to str1 */
    memcpy(str1, str2, sizeof(str2));
 
    puts("\nstr1 after memcpy ");
    puts(str1);
 
    return 0;
}

Output

str1 before memcpy 
Geeks

str1 after memcpy 
Quiz

Important Points about memcpy()

  1. memcpy() doesn’t check for overflow or \0.
  2. memcpy() leads to problems when source and destination addresses overlap.

Note: memmove() is another library function that handles overlapping well.

Related Article

Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above

Last Updated : 08 Jun, 2023
Like Article
Save Article
Similar Reads