C Copy String: strcpy()

The strcpy() function in C is used to copy the contents of one string to another. It is defined in the string.h header file. The function takes two parameters: the destination string and the source string. Here is the syntax:

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

The strcpy() function copies the characters from the source string to the destination string until it encounters a null character ('\0'), which marks the end of the string. It then adds a null character to the destination string to terminate it properly.

Here’s an example usage of strcpy():

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

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

    strcpy(destination, source);

    printf("Source: %s\n", source);
    printf("Destination: %s\n", destination);

    return 0;

In this example, the strcpy() function is used to copy the contents of the source string to the destination string. After the copy operation, both strings are printed, showing that the contents have been successfully copied.

It’s important to ensure that the destination string has enough space to accommodate the copied string, including the null character. If the destination string is not large enough, it may lead to a buffer overflow, causing undefined behavior.