English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structure

C Language File

C Others

C Language Reference Manual

Usage and example of C library function strcpy()

C Standard Library - <string.h>

C library function char *strcpy(char *dest, const char *src) Copy src The string pointed to by dest.

It should be noted that if the target array dest is not large enough and the source string is too long, it may cause a buffer overflow.

Declaration

The following is the declaration of the strcpy() function.

char *strcpy(char *dest, const char *src)

Parameters

  • dest -- A pointer to the target array used to store the copied content.

  • src -- The string to be copied.

Return value

This function returns a pointer to the final target string dest.

Online example

The following example demonstrates the usage 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 oldtoolbag.com");
   strcpy(dest, src);
 
   printf("The target string: %s\n", dest);
   
   return(0);
}

Let's compile and run the above program, which will produce the following result:

The target string: This is oldtoolbag.com

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\n1,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

C Standard Library - <string.h>