In this section we will learn what the strcpy() function is and how to use it in C.
C String Copy: strcpy() Function
Sometimes we want to copy the content of one character-string and place it in another memory location.
This is where we can use the `strcpy` function.
Notes:
- The null `\0` character of the source character-string will be copied as well.
- If there’s a character-string already in the destination memory-location, it will be replaced by the copied character string.
- The prototype of this function exists in the `string.h` header file and so we need to include the header file in order to use the function.
strcpy() Function Syntax
Here’s the prototype of the function:
char* strcpy( char* dest, const char* src );
strcpy() Function Parameters
- The first parameter of the function is the address of the memory location that we want to paste the character-string in there.
- The second argument is the address of the character-string that we want to copy its content.
strcpy() Function Return Value
The returned value of the function is the address of the memory location from which the character-string is placed.
Example: strcpy() in C
#include <stdio.h> #include <string.h> int main() { char destination[100] = "Hi"; char source[] = "Hello to you"; strcpy(destination, source); puts(destination); return 0; }
Output:
Hello to you
How to use strcpy() in C
As you can see, using the strcpy() function, the entire content of the first argument (first character-string) is replaced with the content of the second argument (second character-string).