C strcpy() Function

The strcpy() function in C is used to copy a string from a source to a destination. It copies the content of one string into another, including the null terminator ('0'). This function is defined in the string.h library.

Syntax of strcpy()

The syntax of the strcpy() function is as follows:

Syntax:

                        
char *strcpy(char *dest, const char *src);
                        
                    

The function takes two arguments:

The function returns a pointer to the destination string (dest) after copying the content of the source string into it.

Example of strcpy() Function

Here is an example that demonstrates how the strcpy() function works:

Example:

                        
#include <stdio.h>
#include <string.h>
int main() {
    char src[] = "Hello, World!";
    char dest[50];
    
    // Copying the string from src to dest
    strcpy(dest, src);
    
    // Displaying the copied string
    printf("Source String: %s\n", src);
    printf("Destination String: %s\n", dest);
            
    return 0;
}
                        
                    

Output:

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

Explanation of the Example

In this example:

Example:

                        
#include <stdio.h>
#include <string.h>
int main() 
{
    char input[100], copy[100];
    
    printf("Enter a string: ");
    fgets(input, sizeof(input), stdin);
    
    // Remove newline character added by fgets
    input[strcspn(input, "\n")] = '0';
    
    strcpy(copy, input);
    
    printf("Original string: %s\n", input);
    printf("Copied string: %s\n", copy);
    
    return 0;
}
            
        
                    

Output:

Enter a string: Hellow shorat Original string: Hellow shorat Copied string: Hellow shorat

Important Notes