C Library Function - strcpy()
C Standard Library - <string.h>
Description
The C library function char *strcpy(char *dest, const char *src) copies the string pointed to by src to dest.
It is important to note that if the destination array dest is not large enough, and the length of the source string is too long, it may lead to buffer overflow.
Declaration
Here is the declaration for the strcpy() function.
char *strcpy(char *dest, const char *src)
Parameters
dest -- Pointer to the destination array where the content is to be copied.
src -- The string to be copied.
Return Value
This function returns a pointer to the final destination string dest.
Example
The following example demonstrates the use of the strcpy() function.
Example 1
#include <stdio.h>
#include <string.h>
int main()
{
char src[40];
char dest[100];
memset(dest, '\0', sizeof(dest));
strcpy(src, "This is tutorialpro.org");
strcpy(dest, src);
printf("Final destination string: %s\n", dest);
return(0);
}
Let's compile and run the above program, which will produce the following result:
Final destination string: This is tutorialpro.org
Example 2
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[]="Sample string";
char str2[40];
char str3[40];
strcpy (str2,str1);
strcpy (str3,"copy successful");
printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3);
return 0;
}
Let's compile and run the above program, which will produce the following result:
str1: Sample string
str2: Sample string
str3: copy successful