The ones who are crazy enough to think they can change the world are the ones who do.
- Steve Jobs

strcpy() in C

Purpose of strcpy()

strcpy() is one of the inbuilt string function in c programming which is used to copy one string to another string.

How strcpy() Works

The following diagram clearly illustrate the working principle of strcpy() inbuilt string function in C.

strcpy() in c

In the above diagram strcpy() takes two parameters say str1 and str2. Here str2 act as a destination string whereas str1 act as a source. strcpy() copies source string to the destination string.

Syntax - strcpy()

  • strcpy() accepts two parameters.
  • Both parameters must be a string.
  • To use strcpy() inbuilt string function in C, we need to declare #include<string.h> header file.
Syntax
strcpy(str1, str2);

C Program - strcpy()

Let us work through strrchr() function, In the following program we will find the last occurrence of a character chr in a string str.

c-using-strcpy.c
#include <stdio.h>
#include<string.h>
int main()
{
char str1[30] = "This is strcpy", str2[30];
strcpy(str2, str1);
printf("Original String : %s ", str1);
printf("\nCopied String : %s ", str2);
return 0;
}
Original String : This is strcpy
Copied String : This is strcpy

Note:

The above program defines the function strcpy(), which copies a string from variable str2 to another variable str1.

C Program - Without strcpy()

c-without-strcpy.c
#include <stdio.h>
#include<string.h>
int main()
{
char str1[30] = "This is strcpy";
char str2[30], i;
for(i=0; str1[i]!='\0';i++){
str2[i] = str1[i];
}
str2[i]='\0';
printf("Original String : %s ", str1);
printf("\nCopied String : %s ", str2);
return 0;
}
Original String : This is strcpy
Copied String : This is strcpy

Note:

The above program looks verbose but yields same the result.

Did You Know?

When str2 is already initialized with some other string, strcpy() will replace the string from its source string.

c-strcpy-3.c
#include <stdio.h>
#include<string.h>
int main()
{
char str1[30] = "This is strcpy", str2[30]="Overwite it";
strcpy(str2, str1);
printf("Original String : %s ", str1);
printf("\nCopied String : %s ", str2);
return 0;
}
Original String : This is strcpy
Copied String : This is strcpy

Report Us

We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.

Report