strcpy() Function In C

The strcpy() function is used to copy a given string or character array to the specified character array. The strcpy() function copies all provided strings or characters to the destination if the destination has enough memory area. Also, the terminating null character is added and copied to the end of the destination. If the size of the destination is less than the source thew overflow errors occur. The strcpy() function is provided via the string.h library so in order to use the string.h library should be included.

strcpy() Function Syntax

The strcpy() function has the following simple syntax.

char *strcpy(char *DESTINATION, const char *SOURCE)
  • DESTINATION is the destination memory are which is generally a char pointer where the source string will be stored.
  • SOURCE is the source string or characters which can be a string or character pointer.

strcpy() Function Exaple

In the following example, we will use the strcpy() function in order to copy a character array content into another character array and a string into a character array.

/* strcpy() function example */

#include <stdio.h>
#include <string.h>

int main ()
{
  char s1[]="linuxtect";
  char s2[40];
  char s3[40];
  strcpy (s2,s1);
  strcpy (s3,"wisetut");
  printf (" s1: %s\n s2: %s\n s3: %s\n",s1,s2,s3);
  return 0;
}

The output of the strcpy() example is like below.

s1: linuxtect
s2: linuxtect
s3: wisetut

implicit declaration of function ‘strcpy’

The strcpy() function is provided via the string.h library. So in order to use strcpy() function the string.h library should be included in the related source code. If it is not included the implicit declaration of function strcpy warning and error is thrown like below.

strcpy_example.c: In function ‘main’:
strcpy_example.c:10:3: warning: implicit declaration of function ‘strcpy’ [-Wimplicit-function-declaration]
   10 |   strcpy (s2,s1);
      |   ^~~~~~
strcpy_example.c:10:3: warning: incompatible implicit declaration of built-in function ‘strcpy’
strcpy_example.c:4:1: note: include ‘<string.h>’ or provide a declaration of ‘strcpy’
    3 | #include <stdio.h>
  +++ |+#include <string.h>
    4 | 

Leave a Comment