C++ strcpy()

The strcpy() function in C++ copies a character string from source to destination. It is defined in the cstring header file.

Example

#include <cstring>
#include <iostream>

using namespace std;

int main() {
  char src[] = "Hello Programmers.";
    
  // large enough to store content of src
  char dest[20];

// copy the contents of src to dest strcpy(dest,src);
cout << dest; return 0; } // Output: Hello Programmers.

strcpy() Syntax

The syntax of strcpy() is:

strcpy( char* dest, const char* src );

strcpy() Parameters

The strcpy() function takes the following parameters:

  • dest - pointer to a C-string where the contents are copied to
  • src - pointer to a C-string where the contents are copied from

strcpy() Return Value

The strcpy() function returns:

  • dest (the pointer to the destination C-string)

strcpy() Prototype

The prototype of strcpy() as defined in the cstring header file is:

char* strcpy(char* dest, const char* src);

The strcpy() function copies the C-string pointed to by src to the memory location pointed to by dest. The null terminating character '\0' is also copied.

Notice that:

  • src is of const char* type. The const keyword ensures that the C-string pointed to by src cannot be modified by strcpy().
  • dest is of char* type. The absence of const ensures that the C-string pointed to by dest can be modified by strcpy().

strcpy() Undefined Behavior

The behaviour of strcpy() is undefined if:

  • The memory allocated for dest pointer is not large enough.
  • The strings overlap.

Example: C++ strcpy()

#include <cstring>
#include <iostream>

using namespace std;

int main() {
  char src[20] = "I am the source.";

  // large enough to store content of src
  char dest[30] = "I am the destination.";
    
  cout << "dest[] before copy: " << dest << endl;

// copy contents of src to dest strcpy(dest,src);
cout << "dest[] after copy: " << dest; return 0; }

Output

dest[] before copy: I am the destination.
dest[] after copy: I am the source.

Also Read:

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community