
177 views
memcpy() in C
The memcpy()
function in C is used to copy a block of memory from a source location to a destination location. It is part of the C Standard Library and is often used for copying data from one data structure to another, such as arrays, strings, or structs. The function has the following prototype:
C
void *memcpy(void *dest, const void *src, size_t n);
dest
: A pointer to the destination memory location where the data will be copied.src
: A pointer to the source memory location from which the data will be copied.n
: The number of bytes to copy.
Here’s an example of how to use memcpy()
:
C
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, World!";
char destination[20];
// Copy the contents of 'source' to 'destination'
memcpy(destination, source, strlen(source) + 1);
printf("Source: %s\n", source);
printf("Destination: %s\n", destination);
return 0;
}
In this example:
- We have a source string
source
containing the text “Hello, World!” and a destination character arraydestination
. - We use
memcpy()
to copy the contents ofsource
todestination
. We specify the length of the source string usingstrlen(source) + 1
to ensure that the null-terminator (‘\0’) is also copied. - After copying, both
source
anddestination
contain the same text.
Important points to note about memcpy()
:
- It copies data byte by byte, so it is suitable for copying binary data as well as text.
- It doesn’t perform any type checking, so it treats the memory as an array of bytes.
- It’s important to ensure that the destination buffer has enough space to accommodate the copied data to avoid buffer overflow.
- It’s a low-level memory operation and doesn’t handle memory allocation or resizing.
- The
memcpy()
function returns a pointer to the destination, but this is typically not used since it is the same as thedest
argument.
For safer string and memory operations, especially when working with strings, you may prefer to use functions like strcpy()
for strings and dynamic memory allocation functions such as malloc()
and free()
.