Copy Strings with strcpy() in C++: Syntax, Example, and Safety
This Snippet is coded by a user inOnline cpp Compiler. You can see and run this code too.
زبان: C++
strcpy() copies a null-terminated C-style string from a source buffer to a destination buffer. It is declared in <cstring> as std::strcpy(char* dest, const char* src) and returns dest, so calls can be chained or used in expressions. The function reads characters from src until it reaches '\0', writes each character—including the terminator—to dest, and stops. It does not allocate memory, resize the destination, or check capacity, so dest must be large enough for the entire source string plus the null terminator, and the buffers must not overlap.
In the example, destination[50] safely holds "Hello, strcpy!", while exact[4] holds "C++" plus '\0'. The program prints the source, the copied destination, the copied length using std::strlen, and a second exactly sized copy. Inputs are the destination array and the source string literal. Outputs are the copied strings and their lengths.
Time complexity is O(n), where n is the source string length, because every character is copied once. Extra space is O(1). Avoid overlapping buffers and undersized destinations; otherwise behavior is undefined. For modern C++, prefer std::string, which manages memory automatically and avoids buffer-overflow risks.