What is strcpy() Function in C language?


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

An array of characters is called a string.

Declaration

Following is the declaration for an array

char stringname [size];

For example − char string[50]; string of length 50 characters

Initialization

  • Using single character constant −
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
  • Using string constants −
char string[10] = "Hello":;

Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’

The strcpy ( ) function

  • This function is used for copying source string into destination string.

  • The length of the destination string is greater than or equal to the source string.

Syntax

The syntax is as follows −

strcpy (Destination string, Source String);

Example

The following example shows the usage of strcpy() function.

char a[50]; char a[50];
strcpy ("Hello",a); strcpy ( a,"hello");
output: error output: a= "Hello"

Program

The following program shows the usage of strcpy() function.

 Live Demo

#include <string.h>
main ( ){
   char a[50], b[50];
   printf ("enter a source string");
   scanf("%s", a);
   strcpy ( b,a);
   printf ("copied string = %s",b);
   getch ( );
}

Output

When the above program is executed, it produces the following result −

Enter a source string : Hello
Copied string = Hello

Let’s see another example on strcpy.

Given below is a C program demonstrating strcpy library function −

Program

 Live Demo

#include<stdio.h>
#include<string.h>
void main(){
   //Declaring source and destination strings//
   char source[25],destination[50];
   //Reading Input from user//
   printf("Enter the string to be copied : ");
   gets(source);
   printf("Enter the existing destination string : ");
   gets(destination);
   //Using strcpy library function//
   strcpy(destination,source);
   //Printing destination string//
   printf("Destination string is : ");
   puts(destination);
}

Output

When the above program is executed, it produces the following result −

Enter the string to be copied : C programming
Enter the existing destination string : bhanu
Destination string is : C programming

Updated on: 19-Mar-2021

589 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements