How is the function strcpy used in C language?
The strcpy function is used to copy one string to another. Its syntax is:
char *strcpy(char *dest, const char *src);
In this case, dest is the target string, while src is the source string to be copied.
There are a few things to keep in mind when using the strcpy function:
- The destination string dest must be large enough to accommodate the content of the source string src as well as the null character at the end.
- After the string is copied, the destination string dest will be terminated with a null character ‘\0’.
- The source string src can be a string constant, character array, or pointer to a string.
- The return value is a pointer that points to the destination string, dest.
Sample code:
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello, World!";
char dest[20];
strcpy(dest, src);
printf("源字符串src:%s\n", src);
printf("目标字符串dest:%s\n", dest);
return 0;
}
In the above sample code, the source string “Hello, World!” is copied to the target string dest, and the contents of both strings are ultimately displayed.