Home C++ Strings Functions memcpy() C++ memcpy() Function Definition In C++, memcpy() copies a block of bytes from a source address to a destination address.
The regions must not overlap. Include <cstring>.
This guide shows the C library helper in a C++ .cpp program with std::cout. Prefer std::string for new text code; keep these APIs for C interop and interviews.
Syntax Pass destination, source, and byte count.
std::memcpy(dest, src, n); Call What it does std::memcpy(dest, src, n)Copy n bytes from src to dest.
For overlapping memory, use memmove. For C-strings prefer strcpy/strncpy only with careful sizes—or use std::string.
Library declarations void* memcpy(void* dest, const void* src, size_t n); Parameters Parameter Description destDestination buffer. srcSource buffer. nNumber of bytes to copy.
Return Value Return Value Description void*Equals dest.
C++ Examples 1. Copy array 2. Copy chars 3. Partial copy Example 1 — Basic memcpy() Copy ints between arrays.
#include <cstring>
#include <iostream>
int main() {
int a[3] = {1, 2, 3};
int b[3] = {};
std::memcpy(b, a, sizeof a);
std::cout << b[0] << b[1] << b[2] << '\\n';
return 0;
} How It Works Source holds 1,2,3. memcpy copies the raw bytes into b. All three values appear. Example 2 — Copy a Char Buffer Copy five characters.
#include <cstring>
#include <iostream>
int main() {
char src[] = "Hello";
char dst[6];
std::memcpy(dst, src, 6);
std::cout << dst << '\\n';
return 0;
} How It Works Six bytes include the null terminator. Destination becomes a printable C-string. cout prints Hello. Example 3 — Copy Part Copy only two bytes.
#include <cstring>
#include <iostream>
int main() {
char src[] = "ABCD";
char dst[3] = {};
std::memcpy(dst, src, 2);
std::cout << dst << '\\n';
return 0;
} How It Works Only two bytes are copied. dst still has a trailing null from initialization. Print shows AB. Frequently Asked Questions What does memcpy do? It copies n bytes from src to dest.
Can the buffers overlap? No. Use memmove if they might.
Header? <cstring> in C++.
Does it add a null terminator? No. It copies exactly n bytes.
Safer alternative for text? Prefer std::string for owning text.
Next: memmove() Keep going through the string functions. Copy bytes; safe when source and destination overlap.
memmove() tutorial → CODETOFUN NEWS
Stay Ahead in Tech Get the latest IT news, programming updates, and technology trends directly on your phone.
About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
7 people found this page helpful
Helpful Share Copy link Suggestion