C++ memcpy() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
<cstring>

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.

C++
std::memcpy(dest, src, n);
CallWhat 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
C++
void* memcpy(void* dest, const void* src, size_t n);

Parameters

ParameterDescription
destDestination buffer.
srcSource buffer.
nNumber of bytes to copy.

Return Value

Return ValueDescription
void*Equals dest.

C++ Examples

Example 1 — Basic memcpy()

Copy ints between arrays.

C++
#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

  1. Source holds 1,2,3.
  2. memcpy copies the raw bytes into b.
  3. All three values appear.

Example 2 — Copy a Char Buffer

Copy five characters.

C++
#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

  1. Six bytes include the null terminator.
  2. Destination becomes a printable C-string.
  3. cout prints Hello.

Example 3 — Copy Part

Copy only two bytes.

C++
#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

  1. Only two bytes are copied.
  2. dst still has a trailing null from initialization.
  3. Print shows AB.

Frequently Asked Questions

It copies n bytes from src to dest.
No. Use memmove if they might.
<cstring> in C++.
No. It copies exactly n bytes.
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.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

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