strcpy() in C++

Video Tutorial
FREE
Strlen,Strcpy methods thumbnail
This video belongs to
C++ Course: Learn the Essentials
14 modules
Certificate
Topics Covered

Overview

The strcpy function in C++ creates a copy of the string and replaces the other string with that copy, i.e., copies one string content to another. It is present in the cstring header file.

Syntax of strcpy() in C++

The syntax of this function is:

src is the string whose content is going to be copied, and dest is the string where the content is going to be copied.

Parameters of Strcpy() in C++

This function takes two input parameters as follows.

  • src: This is the pointer to the string to be copied. const char* type of source string ensures that the function will not change the content of the source string.
  • dest: This is the pointer to the array where the other string will be copied. dest is not of type const because the function changes the content of the destination string.

Return Value of Strcpy() in C++

The strcpy function in C++ returns a pointer to the dest string after copying the other string. Let's see an example to understand the strcpy function.

Example

Output

As we see from above, the output src string content gets copied to the dest string using the strcpy() function.

What is strcpy() in C++?

The strcpy function in C++ is used to copy the content of the source string to the destination string without changing the source string. It returns a pointer to the destination string after copying its content.

A few points we need to remember while using strcpy in C++ are as follows:

  • This function only takes C style strings (char str[]) in its input parameters. So it doesn't work with C++ style strings (string s).
  • Since the function creates a copy of the string referred to by the src pointer, it doesn't affect the source string.
  • The size of the destination string must be large enough to contain the source string(including the null character).
  • The destination string and the source string should not overlap in memory.

Output

Conclusion

  • The strcpy function in C++ creates a copy of the string and replaces the other string with this.
  • It is defined in the cstring header file.
  • Both the input parameters must be C-style strings. This function doesn't accept C++ strings as input.
  • The size of the destination array must be large enough to contain the source array.