The strcpy() Function in C

The syntax of the strcpy() function is:

Syntax: char* strcpy (char* destination, const char* source);

The strcpy() function is used to copy strings. It copies string pointed to by source into the destination. This function accepts two arguments of type pointer to char or array of characters and returns a pointer to the first string i.e destination. Notice that source is preceded by the const modifier because strcpy() function is not allowed to change the source string.

The following program demonstrates the strcpy() function in action.

Expected Output:

It is important to note that strcpy() function do not check whether the destination has enough size to store all the characters present in the source. It is the responsibility of the program to make sure that the destination array has enough space to accommodate all the characters of the source string.

Another important point to note about strcpy() is that you should never pass string literals as a first argument. For example:

Here you are trying to copy the contents of ch_arr to “destination string” which is a string literal. Since modifying a string literal causes undefined behaviour, calling strcpy() in this way may cause the program to crash.

Let’s create our own version of strcpy() function.

How it works:

The my_strcpy() function accepts two arguments of type pointer to char or (char*) and returns a pointer to the first string.

In line 18, we have assigned the base address of the destination to start, this is necessary otherwise we will lose track of the address of the beginning of the string.

In line 20, we have while loop, the while loops copies character from source to destination one by one. Copying stops when source points to the address of the null character ('\0').

At this point string pointed to by start contains all characters of the source except null character ('\0'). The statement in line 13, appends a null character ('\0') to the string.

In line 14, the return statement returns the character pointer to the calling function.

Let’s rewrite our previous program, incorporating the definition of my_strcpy() function.

Expected Output:

The output of strcpy() and my_strcpy() is same that means our program is working as expected.

Leave a Comment