C: Copying data using the memcpy() function in C

In C, the memcpy() function copies n number of characters from one block of memory to another.

svg viewer

Syntax

The general syntax for the memcpy() function is:

void * memcpy(void *destination, const void *source, size_t n);

Parameters

Let’s look at the parameters that the memcpy() function takes as input:

  • Destination: Pointer to the destination array where data will be copied.

  • Source: Pointer to the source of the data to copy.

  • N: The number of characters to copy.

Note:

  1. The pointers have been declared void * so that they may be used for any data type.
  2. The memcpy() function does not check for the terminating null character \0 and only copies n characters of a string.

Return value

The function returns a pointer to the destination string.

Example

Let’s look at a simple example of copying a string from one array to another using the memcpy() function.

In case of overlapping memory segments, the memcpy() function ceases to work properly, i.e. if you wish to copy characters within the same block of memory, the memcpy() function does not function as desired and therefore is not recommended for use.

#include<stdio.h>
#include<string.h>
int main()
{
char source[] = "World";
char destination[] = "Hello ";
/* Printing destination string before memcpy */
printf("Original String: %s\n", destination);
/* Copies contents of source to destination */
memcpy (destination, source, sizeof(source));
/* Printing destination string after memcpy */
printf("Modified String: %s\n", destination);
return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved