strcpy function in c

strcpy() function in c

Declaration:

char *strcpy(char *str1,const char str2);

This strcpy() is used to copy one string to another string. The strcpy(str1,str2) copies string str2 into the str1 with the null character. Here str2 is the source string and str1 is the designation str string. The old contents of the designation string str1 are lost. Then the function returns the pointer to the designation string str1. so in this the designation string should be character pointer or character array or a char pointer initialized to dynamically allocated memory. so the designation string can not be string constant beacuse it has to be modified. for example the function call strcpy(“india”,str1) or strcpy(“india”,”Uttarpradesh”) are wrong because india is a string constant so we can not overwrite it.

Note: The programmer should know in already that the designation array has capability to store source string or second string.

/* use of strcpy() */
#include<stdio.h>
#include<string.h>
int
main()
{
char str1[15];
char str2[15];
printf("Enter the string");
scanf("%s",&str2);
strcpy(str1,str2);
printf("The first string = %s \t and second string =%s \n ",str1,str2);
strcpy(str1,"Uttar");
strcpy(str2,"Pradesh");
printf("The first string = %s \t and second string =%s \n",str1,str2);
return 0;
}

output:
Enter the string India
The first string = Inida and second string = India
The first string = Uttar and second string = pradesh

/* use of strcpy() */
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "programmingknow";
char str2[20]; // empty
// copying str1 into str2
strcpy(str2, str1);
puts(str2); // programmingknow
return 0;
}

output:
programmingknow