The strcpy() function copies one string to another string.
C strcpy() function declaration
char *strcpy(char *str1, const char *str2)
str1 – This is the destination string where the value of other string str2 is copied. First argument in the function
str2 – This is the source string, the value of this string is copied to the destination string. This is the second argument of the function.
Return value of strcpy()
This function returns the pointer to the destination string or you can say that it returns the destination string str1.
Example: strcpy() function
#include <stdio.h> #include <string.h> int main () { char str1[20]; char str2[20]; //copying the string "Apple" to the str1 strcpy(str1, "Apple"); printf("String str1: %s\n", str1); //copying the string "Banana" to the str2 strcpy(str2, "Banana"); printf("String str2: %s\n", str2); //copying the value of str2 to the string str1 strcpy(str1, str2); printf("String str1: %s\n", str1); return 0; }
Output:
String str1: Apple String str2: Banana String str1: Banana
As I have mentioned in the beginning of the post that this function returns the pointer to the destination string which means if we display the return value of the function that it should display the value of the destination string after copying the source string to it. Lets take an example to understand this.
#include <stdio.h> #include <string.h> int main () { char str[20]; /* copying the string "Apple" to the str and * displaying the return value of strcpy() */ printf("Return value of function: %s\n", strcpy(str, "Apple")); printf("String str1: %s\n", str); return 0; }
Output:
Return value of function: Apple String str1: Apple
Leave a Reply