strcpy() function in C Programming Language
Table of Content:
strcpy( ) function copies contents of one string into another string. Syntax for strcpy function is given below.
Syntax
char *strcpy(char *str1, const char *str2);
Parameters
The strcpy( )
function copies the contents of str2 into str1. str2 must be a pointer to a null-
terminated string. The strcpy( )
function returns a pointer to str1.
In C99, str1 and str2 are qualified by restrict.
If str1 and str2 overlap, the behavior of strcpy( ) is undefined.
Methods | Description |
strcpy ( str1, str2); |
It copies contents of str2 into str1. |
strcpy ( str2, str1); |
It copies contents of str1 into str2. |
Program
In this program, source string " Welcome" is copied into target string using strcpy( )
function.
#include#include int main( ) { char source[ ] = " Welcome" ; char target[20]= "to atnyla" ; printf ( "\nsource string = %s", source ) ; printf ( "\ntarget string = %s", target ) ; strcpy ( target, source ) ; printf ( "\ntarget string after strcpy( ) = %s", target ) ; return 0; }
Output
source string = Welcome target string = to atnyla target string after strcpy( ) = Welcome
Points to be Noted
If destination string length is less than source string, entire source string value won’t be copied into destination string.
For example, consider destination string length is 20 and source string length is 30. Then, only 20 characters from source string will be copied into destination string and remaining 10 characters won’t be copied and will be truncated.