In C, the memcpy()
function copies n
number of characters from one block of memory to another.
The general syntax for the memcpy()
function is:
void * memcpy(void *destination, const void *source, size_t n);
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:
- The pointers have been declared
void *
so that they may be used for any data type.- The
memcpy()
function does not check for the terminating null character\0
and only copiesn
characters of a string.
The function returns a pointer to the destination string.
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