The C programming language provides the memcpy()
method in order to copy data from the source memory location to the destination memory location. The memcpy() method is provided by the string.h
library for C. Also the memcpy() method is provided with the C++ standard library.
memcpy() Method Syntax
The memcpy() method has the following syntax where 3 parameters should be provided.
*memcpy(void *DEST, const void *SRC, size_t SIZE)
- *DEST is the destination memory location pointer where the data will be copied to. The type of the *DEST is void which means any type like interger, char can be used as destination memory location.
- *SRC is the source memory location pointer where the data will be copied from. The type of the *SRC is void and const as we can provide any type which is also constant.
- SIZE is the number of the bytes we want to copy.
Copy Bytes with memcpy()
The memcpy() command generally used copy bytes from specified pointer to location to the destination pointer location. In the following example, we copy an integer array named src
to the dst
.
#include <stdio.h>
#include <string.h>
int main () {
const int src[4] = [1,2,3,4];
char dest[4];
memcpy(dest, src, 4);
return(0);
}
Copy String with memcoy()
Another popular case for the memcpy() method is copying the string. As you know strings are character arrays in the C programming language.
#include <stdio.h>
#include <string.h>
int main ()
{
char src[] = "Linux";
char dst[] = "Tect";
puts("dst before memcpy ");
puts(dst);
/* Copies contents of str2 to str1 */
memcpy (src, dst, sizeof(src));
puts("\ndst after memcpy ");
puts(dst);
return 0;
}
memcpy() vs memcmp()
The memcpy()
is the short form of the memory copy
but it can be easily misused as memcmp()
which is a different function with different output. Interestingly the memcpy() and memcmp() methods accept the same number of parameters with the same types.