The strcpy() function in C++ copies a character string from source to destination. It is defined in the cstring header file.
Example
strcpy() Syntax
The syntax of strcpy() is:
strcpy( char* dest, const char* src );
strcpy() Parameters
The strcpy() function takes the following parameters:
- dest - pointer to a C-string where the contents are copied to
- src - pointer to a C-string where the contents are copied from
strcpy() Return Value
The strcpy() function returns:
- dest (the pointer to the destination C-string)
strcpy() Prototype
The prototype of strcpy() as defined in the cstring header file is:
char* strcpy(char* dest, const char* src);
The strcpy() function copies the C-string pointed to by src to the memory location pointed to by dest. The null terminating character '\0' is also copied.
Notice that:
- src is of
const char*type. Theconstkeyword ensures that the C-string pointed to by src cannot be modified bystrcpy(). - dest is of
char*type. The absence ofconstensures that the C-string pointed to by dest can be modified bystrcpy().
strcpy() Undefined Behavior
The behaviour of strcpy() is undefined if:
- The memory allocated for dest pointer is not large enough.
- The strings overlap.
Example: C++ strcpy()
Output
dest[] before copy: I am the destination. dest[] after copy: I am the source.