C Copy String: strcpy()

In the C programming language, the strcpy() function is used to copy one string to another. It is a part of the string.h library and is commonly used for manipulating strings.

Syntax

The syntax of the strcpy() function is:

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

Parameters

The strcpy() function takes two parameters:

  • destination: This is a pointer to the destination string where the copied string will be stored.
  • source: This is a pointer to the source string which will be copied.

Return Value

The strcpy() function returns a pointer to the destination string.

Example

Here is an example that demonstrates the usage of the strcpy() function:

#include <stdio.h>
#include <string.h>

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

    strcpy(destination, source);

    printf("Copied string is: %sn", destination);

    return 0;
}

In this example, the strcpy() function is used to copy the contents of the source string to the destination string. The destination string is then printed using the printf() function.

The output of this program will be:

Copied string is: Hello, World!

Explanation

The strcpy() function copies the characters from the source string to the destination string until it encounters a null character (''). It then adds a null character at the end of the destination string to mark the end of the copied string.

It is important to note that the destination string must have enough space to hold the copied string. If the destination string is not large enough, it may lead to buffer overflow and undefined behavior.

The strcpy() function is a useful function in C for copying strings. It allows you to easily copy the contents of one string to another. However, it is important to ensure that the destination string has enough space to hold the copied string to avoid any potential issues.

Scroll to Top