C++ String strcpy() Function

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
C-strings / buffers

What You’ll Learn

The strcpy() function copies a null-terminated C-string from a source pointer into a writable destination buffer. It is one of the oldest string utilities in C and C++—essential for understanding how character arrays work before you move to safer std::string in modern code.

01

Copy Text

Source to buffer.

02

Null Terminator

Includes \0.

03

Return dest

Pointer returned.

04

Buffer Size

Must fit all chars.

05

vs strncpy

Bounded copy.

06

std::string

Safer modern way.

Definition and Usage

In C++, strcpy() is declared in <cstring>. It walks the source string character by character, writing each byte into destination until it reaches and copies the terminating null character ('\0').

Unlike C++ assignment with std::string, you cannot copy into a char[] array with =. Arrays decay to pointers and would only copy addresses, not text. strcpy() performs the actual byte-by-byte copy that beginners often expect from the assignment operator.

💡
Beginner Tip

Before calling strcpy(dest, src), make sure dest has at least strlen(src) + 1 bytes. The + 1 is for the null terminator. If the buffer is too small, the program may crash or behave unpredictably.

📝 Syntax

Function signature and a typical call:

C++
#include <cstring>

char* strcpy(char* destination, const char* source);

// Example:
char buffer[20];
strcpy(buffer, "Hello, C++!");

Parameters

  • destination — writable char array or allocated memory that will receive the copy.
  • source — null-terminated C-string to copy from (not modified).

Return Value

Returns destination (the same pointer passed as the first argument). The destination buffer now holds a duplicate of the source string.

⚡ Quick Reference

FunctionWhat it doesSize check?
strcpy()Copy full source stringNo — you must ensure space
strncpy()Copy at most n charactersPartial — may omit \0
strcat()Append source to destinationNo — dest must have room
std::string =Copy C++ string objectAutomatic sizing
Copy
strcpy(dest, src)

Full string copy

Min size
strlen(src) + 1

Bytes needed

Return
char* dest

Same as 1st arg

Include
#include <cstring>

Header file

Examples Gallery

Compile with g++ strcpy.cpp -std=c++17 -o strcpy. Every example uses a destination buffer large enough for the source string plus the null terminator.

📚 Getting Started

Copy a literal string into a char array and print both sides.

Example 1 — Basic strcpy() Usage

Copy "Hello, C++!" from a source pointer into a 20-byte destination array.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* source = "Hello, C++!";
    char destination[20]; // Room for 12 chars + '\0' and extra space

    std::strcpy(destination, source);

    std::cout << "Source:      " << source << "\n";
    std::cout << "Destination: " << destination << "\n";

    return 0;
}

How It Works

strcpy copies each character from source into destination, including the final '\0'. After the call, both pointers refer to strings with the same text (in different memory locations).

Example 2 — Using the Return Value

strcpy returns destination, so you can print immediately from the returned pointer.

C++
#include <iostream>
#include <cstring>

int main() {
    char label[32];
    const char* title = "CodeToFun";

    std::cout << "Copied: " << std::strcpy(label, title) << "\n";
    std::cout << "Same buffer: " << label << "\n";

    return 0;
}

How It Works

The return value is not a new string—it is the same address as label. Libraries return it for chaining in C code; in C++ you usually call strcpy and then use the destination variable directly.

📈 Practical Patterns

Initialize buffers, understand why assignment fails, and copy with size awareness.

Example 3 — Copy Into a Fresh Buffer

Start with an uninitialized char array and fill it with a user-facing message.

C++
#include <iostream>
#include <cstring>

int main() {
    char greeting[64];
    const char* defaultMsg = "Welcome to C++ strings!";

    std::strcpy(greeting, defaultMsg);

    // Later, replace the whole message:
    std::strcpy(greeting, "Ready to learn strcpy()?");

    std::cout << greeting << "\n";
    return 0;
}

How It Works

Each strcpy overwrites the entire destination string from the start. Old content after the new terminator is irrelevant because C-strings end at the first '\0'.

Example 4 — Why char Arrays Need strcpy()

You cannot copy text between two char arrays with =—that would copy pointers, not characters.

C++
#include <iostream>
#include <cstring>
#include <string>

int main() {
    const char* source = "Tutorial";
    char destA[20];
    std::string destB;

    // Correct for char arrays:
    std::strcpy(destA, source);

    // Correct for std::string:
    destB = source;

    std::cout << "char[] copy: " << destA << "\n";
    std::cout << "std::string: " << destB << "\n";

    return 0;
}

How It Works

char destA[20] = source; is invalid because arrays are not assignable after declaration. strcpy (or std::string) is the idiomatic way to copy text content.

Example 5 — Copy Only When the Buffer Fits

Check length before copying—a pattern every beginner should learn before using raw strcpy on unknown input.

C++
#include <iostream>
#include <cstring>

bool safeCopy(char* dest, std::size_t destSize, const char* src) {
    std::size_t needed = std::strlen(src) + 1;
    if (needed > destSize) {
        return false;
    }
    std::strcpy(dest, src);
    return true;
}

int main() {
    char buffer[16];
    const char* shortName = "Ada";
    const char* longName  = "Christopher";

    if (safeCopy(buffer, sizeof buffer, shortName)) {
        std::cout << "Copied: " << buffer << "\n";
    }

    if (!safeCopy(buffer, sizeof buffer, longName)) {
        std::cout << "Skipped copy — buffer too small for \"" << longName << "\"\n";
    }

    return 0;
}

How It Works

sizeof buffer gives total bytes in the array. Compare with strlen(src) + 1 before calling strcpy. In production code, prefer std::string or platform-specific bounds-checked functions like strcpy_s when available.

🚀 Common Use Cases

  • Duplicating a C-string — store a copy in your own buffer when the original pointer may change or go out of scope.
  • Initializing char arrays — fill a fixed buffer after declaration when = is not available.
  • Legacy C APIs — many libraries expect null-terminated char* buffers you prepare with strcpy.
  • Embedded / constrained systems — fixed-size buffers without dynamic allocation.
  • Learning pointer semantics — understand why C++ strings and C arrays behave differently.

🧠 How strcpy() Works

1

Read source byte

Start at the first character of source.

Read
2

Write to destination

Copy the byte into the next slot of destination.

Write
3

Advance both pointers

Move to the next character and repeat until '\0' is copied.

Loop

Return destination

Destination is now a null-terminated duplicate of source. No size check was performed along the way.

📝 Notes

  • The destination buffer must have room for all characters plus '\0'.
  • strcpy does not allocate memory—you provide the buffer.
  • Source and destination must not overlap; use memmove for overlapping regions.
  • Passing nullptr to either argument causes undefined behavior.
  • For new C++ projects, std::string assignment avoids manual buffer sizing entirely.

⚡ Optimization

strcpy() is highly optimized in standard libraries and is fine for small, fixed buffers when sizes are known at compile time. If you copy large strings often, consider storing data in std::string to avoid repeated manual length checks and to get move semantics. Avoid calling strlen before every strcpy when the source length is already known (e.g., string literals).

Conclusion

strcpy() is the classic way to copy C-strings into a char buffer. Master the rule strlen(source) + 1 bytes in the destination, never copy into overlapping memory, and prefer std::string when you do not need raw arrays.

Next, explore strcspn() to measure how many initial characters are not in a given set—useful for parsing and tokenization.

💡 Best Practices

✅ Do

  • Ensure dest has at least strlen(src) + 1 bytes
  • Include <cstring> and use std::strcpy in C++
  • Prefer std::string for dynamic text in new code
  • Check sizes before copying unknown or user input
  • Zero-initialize buffers when clarity matters

❌ Don’t

  • Copy into a buffer smaller than the source string
  • Use = between two char[] arrays for text
  • Copy between overlapping memory regions with strcpy
  • Assume strncpy always adds '\0' automatically
  • Ignore return values when debugging—they confirm which buffer was written

Key Takeaways

Knowledge Unlocked

Five things to remember about strcpy()

Use these points whenever you copy C-strings by hand.

5
Core concepts
🔢 02

Return dest

First argument back.

Return
🛡 03

Buffer Size

Your responsibility.

Safety
🔄 04

No Overlap

Use memmove.

Rule
💬 05

std::string

Modern alternative.

C++

❓ Frequently Asked Questions

strcpy() copies every character from a source null-terminated C-string into a destination char array, including the final '\0' terminator. It returns a pointer to destination. The destination buffer must already exist and be large enough to hold the entire source string.
char* strcpy(char* destination, const char* source); Include <cstring>. Call strcpy(dest, src) where dest is a writable char array (or allocated memory) and src is the string to copy.
It returns destination—the same pointer you passed as the first argument. This lets you chain or reuse the result, though most code simply ignores the return value.
It is safe only when the destination buffer is guaranteed large enough (strlen(source) + 1 bytes). If the source is longer than the buffer, strcpy() writes past the end—undefined behavior and a classic buffer overflow. Prefer std::string in new C++ code, or bounded alternatives like strncpy with careful null termination.
strcpy() copies until the source '\0' and always writes a terminator if the buffer is big enough. strncpy() copies at most n characters and may leave destination unterminated if the source is longer than n. Neither checks buffer size automatically—you must size buffers yourself.
No. strcpy() requires non-overlapping memory. Copying within the same buffer or between overlapping regions is undefined behavior. Use memmove() for overlapping copies.
Did you know?

The name strcpy stands for string copy. It has existed since early C because arrays cannot be assigned like variables. Decades later, buffer overflows from unchecked strcpy calls remain a top security lesson—which is why modern C++ favors std::string.

Continue the String Functions Series

Copy strings safely with strcpy(), then learn character-set scanning with strcspn().

Next: strcspn() →

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.

6 people found this page helpful