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:
- dest: A pointer to the destination array where the content of the source string will be copied.
- src: A pointer to the source string that will be copied.
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!
Destination String: Hello, World!
Explanation of the Example
In this example:
- We define a source string
src
with the value "Hello, World!". - We create a destination string
dest
with enough space to hold the copied string. - We use
strcpy()
to copy the contents ofsrc
intodest
. - Both the source and destination strings are printed to show that the content of
src
has been successfully copied todest
.
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
- The
strcpy()
function does not check for buffer overflow. The destination array must have enough space to hold the source string including the null terminator ('0'). If the destination array is too small, it will result in undefined behavior or memory corruption. - It is safer to use the
strncpy()
function if you need to limit the number of characters copied to avoid buffer overflow.