Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

C++ cstring strcpy() Function



The C++ cstring strcpy() function is used to copy a string from one memory location to another memory location.

It works by copying the string until it reaches the null character '\0'. It is important to keep in mind that the destination string must have enough space to store the source string. If the destination string is smaller than the source string, it will cause a buffer overflow. This function takes two arguments, the destination string and the source string.

Syntax

The syntax of the C++ cstring strcpy() function is −

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

Parameters

Following are the parameters of the strcpy() function −

  • destination: Pointer to the destination array where the content is to be copied.

  • source: Pointer to the source of data to be copied.

Return Value

The strcpy() function returns a pointer to the destination, which is the same as the destination pointer passed as the first argument.

Example 1

In this example, we will try to copy the content of one string to another string using the strcpy() function.

#include <iostream>
#include <cstring>

using namespace std;

int main() {
    char source[] = "Hello, World!";
    char destination[100];

    // Copying the content of source string to destination string
    strcpy(destination, source);

    cout << "Source: " << source << endl;
    cout << "Destination: " << destination << endl;

    return 0;
}

Output

When you run the program, the output will be −

Source: Hello, World!
Destination: Hello, World!

Example 2

In this example, we will us take less space in the destination string than the source string. We will then copy the content of the source string to the destination string using the strcpy() function.

#include <iostream>
#include <cstring>

using namespace std;

int main() {
    char source[] = "Hello, World!";
    char destination[4];

    // Copying the content of source string to destination string
    strcpy(destination, source);

    cout << "Source: " << source << endl;
    cout << "Destination: " << destination << endl;

    return 0;
}

Output

When you run the program, the output will be:

Source:  , World!
Destination: Hello, World!

As you can see the output, it is not what we had expected. Output may vary depending on the compiler and the system you are using. It is always recommended to use the strncpy() function instead of strcpy() function to avoid buffer overflow.

Advertisements