memcpy() in C (original) (raw)

Last Updated : 3 Jun, 2026

The memcpy() function in C is used to copy a specified number of bytes from one memory location to another. It is widely used for copying arrays, structures, and blocks of memory efficiently.

#include <stdio.h> #include <string.h>

int main() {

// Initialize a variable
int a = 20;
int b = 10;

printf("Value of b before calling memcpy: %d\n", b);

// Use memcpy to copy the value of 'a' into 'b'
memcpy(&b, &a, sizeof(int)); 

printf("Value of b after calling memcpy: %d\n", b);

return 0;

}

`

Output

Value of b before calling memcpy: 10 Value of b after calling memcpy: 20

**Explanation

Syntax

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

**Parameters

**Return Value: Returns a pointer to the destination memory location (to).

**Note: The source and destination memory regions must not overlap. If overlapping memory regions need to be copied, use memmove() instead.

Copying a String using memcpy()

The memcpy() function can also be used to copy the contents of one character array (string) to another.

C `

#include <stdio.h> #include <string.h>

int main() { char str1[] = "Geeks"; char str2[6] = "";

// Copies contents of str1 to str2
memcpy(str2, str1, sizeof(str1));

printf("str2 after memcpy:");
printf("%s",str2);

return 0;

}

`

Output

str2 after memcpy:Geeks

**Explanation

Behavior and Limitations of memcpy()

The memcpy() function is optimized for fast memory copying, but it has certain characteristics and limitations that should be understood to avoid unexpected behavior.