Open In App

strcpy in C

INTRODUCTION:

strcpy is a C standard library function that copies a string from one location to another. It is defined in the string.h header file.

The function takes two arguments: a destination buffer where the copied string will be stored, and a source string that will be copied. The function copies the entire source string, including the null terminator, into the destination buffer.



The C strcpy() function copies the content of a string to another. The content of the destination string will be replaced with that of the source string by the strcpy() function. It is defined inside <string.h> header file.

Syntax:



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

Parameters: This method accepts the following parameters:

Return Value: A pointer to the destination string is returned after the strcpy() function copies the source string.

Example: 1 




// C program to illustrate
// strcpy() function in C
#include <stdio.h>
#include <string.h>
 
int main()
{
    char str1[] = "Hello World!";
    char str2[] = "GfG";
    char str3[40];
    char str4[40];
    char str5[] = "GeeksForGeeks";
 
    strcpy(str2, str1);
    strcpy(str3, "Copy successful");
    strcpy(str4, str5);
    printf("str1: %s\nstr2: %s\nstr3: %s\nstr4:%s\n", str1,
           str2, str3, str4);
    return 0;
}

Output
str1: Hello World!
str2: Hello World!
str3: Copy successful
str4:GeeksForGeeks

EXAMPLE 2 : 




#include <stdio.h>
#include <string.h>
 
int main()
{
    char str1[20] = "Hello";
    char str2[20];
 
    strcpy(str2, str1);
 
    printf("str1: %s\n", str1);
    printf("str2: %s\n", str2);
 
    return 0;
}

Output
str1: Hello
str2: Hello

Important Points

ADVANTAGES AND DISADVANTAGES:

Some advantages of using strcpy in C include:

It is a simple and easy-to-use function that can be used to copy strings quickly and easily.
It is a standard library function, so it is widely available and portable across different platforms and compilers.
It is relatively fast, as it only requires a single pass through the source string to copy it.

However, there are also some disadvantages to consider when using strcpy:

It does not check the size of the destination buffer, so it is possible to overwrite the buffer and cause a buffer overflow if the source string is longer than the destination buffer. This can lead to security vulnerabilities and other problems.
It does not handle overlapping strings properly. If the source and destination strings overlap, the behavior of strcpy is undefined.
It does not handle null characters within the source string properly. If the source string contains a null character, strcpy will stop copying at that point, even if there are additional characters in the source string.


Article Tags :