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.
Fundamentals
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.
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.
Cheat Sheet
⚡ Quick Reference
Function
What it does
Size check?
strcpy()
Copy full source string
No — you must ensure space
strncpy()
Copy at most n characters
Partial — may omit \0
strcat()
Append source to destination
No — dest must have room
std::string =
Copy C++ string object
Automatic 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
Hands-On
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;
}
📤 Output:
Source: Hello, C++!
Destination: Hello, C++!
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.
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;
}
📤 Output:
Ready to learn strcpy()?
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.
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.
Copied: Ada
Skipped copy — buffer too small for "Christopher"
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.
Applications
🚀 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.
Important
📝 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.
Performance
⚡ 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).
Wrap Up
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.
Copy between overlapping memory regions with strcpy
Assume strncpy always adds '\0' automatically
Ignore return values when debugging—they confirm which buffer was written
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about strcpy()
Use these points whenever you copy C-strings by hand.
5
Core concepts
📝01
Full Copy
Every char + \0.
Basics
🔢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.