Home C++ Strings Functions memccpy() C++ memccpy() Function Definition memccpy copies bytes from source to destination until it has copied a specified byte, or until n bytes are copied.
It is POSIX and in C23. On some Windows toolchains it may be missing—examples show the idea with a small portable loop when needed.
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 When available:
// POSIX / C23:
// void* p = memccpy(dest, src, c, n); Call What it does memccpy(dest, src, c, n)Copy until byte c is copied or n reached.
Return value points just after the copied c, or is null if c was not copied within n bytes.
Library declarations void* memccpy(void* dest, const void* src, int c, size_t n); Parameters Parameter Description dest, src Destination and source. c Stop byte (after it is copied). n Maximum bytes to copy.
Return Value Return Value Description pointer or null Past the copied stop byte, else nullptr.
C++ Examples 1. Portable copy-until 2. Respect n 3. No stop byte Example 1 — Teach the memccpy Idea Copy until comma with a loop (portable).
#include <iostream>
int main() {
const char src[] = "ab,cd";
char dest[8] = {};
std::size_t i = 0;
for (; i < sizeof src - 1 && i < 7; ++i) {
dest[i] = src[i];
if (src[i] == ',') break;
}
std::cout << dest << '\\n';
return 0;
} How It Works We copy characters including the comma. Loop stops after copying ','. Printed buffer is ab, Example 2 — Stop by Count Copy at most two bytes.
#include <cstring>
#include <iostream>
int main() {
char src[] = "WXYZ";
char dest[5] = {};
std::memcpy(dest, src, 2);
std::cout << dest << '\\n';
return 0;
} How It Works Only two bytes are taken. Null from initialization keeps it printable. Shows limiting a copy by count. Example 3 — Copy Without Hit When stop byte is absent, copy n bytes.
#include <cstring>
#include <iostream>
int main() {
char src[] = "abcd";
char dest[5] = {};
std::memcpy(dest, src, 4);
std::cout << dest << '\\n';
return 0;
} How It Works No early stop in this demo. Four bytes are copied. Result is abcd. Frequently Asked Questions What is memccpy? A copy that stops after copying a given byte or after n bytes.
Is it standard C++? It is POSIX/C23; C++ support depends on the library.
Return value? Pointer past the stop byte, or null if not found within n.
Portable alternative? A small loop or memcpy with your own scan.
Safer text handling? Use std::string.
Next: memchr() Keep going through the string functions. Search for a byte in a memory block.
memchr() 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.
13 people found this page helpful
Helpful Share Copy link Suggestion