Search⌘ K

Copying String

Explore how to copy strings in C with the standard strcpy function and develop your own version, xstrcpy. Understand the step-by-step mechanism of copying each character, incrementing pointers, and terminating strings correctly. This lesson helps you master string copying by dissecting different implementations for efficiency and clarity.

The strcpy() function

strcpy( ) copies the source string, str1, into the target string, str2. The basic syntax of the strcpy() function is given below:

char* strcpy(const char *str2, const char *str1);

strcpy( ) takes two strings in its input and, then, copies one string into the other, character by character. The order of passing base addresses to strcpy( ) must always be the target, followed by the source. Here, *str2 points to the target string, and *str1 points to the source string.

See the code given below!

C
# include <stdio.h>
# include <string.h>
int main( )
{
// Initializing string
char str1[] = "Nagpur" ;
char str2[ 10 ] ;
printf("Before copying\n");
printf("Source string: %s \n", str1);
printf("Target string: %s \n\n", str2);
// Copying strings
strcpy ( str2, str1 ) ;
printf("After copying\n");
printf("Source string: %s \n", str1);
printf("Target string: %s \n\n", str2);
}

The xstrcpy() function

Instead of ...