C++: strcpy Function copies null?
You are correct. For the effect you initially expected, you would use strncopy
. strncopy
copies the null terminator as long as you specify the correct length of the string that is being copied.
Your reasoning regarding the copying of the terminating character is correct. The C++ standard (which is the definitive specification for the language) defers to C on this matter (for example, C++14 defers to C99, and C++17 defers to C11).
The C11 standard has this to say about strcpy
:
7.24.2.3 The
strcpy
functionSynopsis:
#include <string.h>
char *strcpy(char * restrict s1, const char * restrict s2);
Description:
The
strcpy
function copies the string pointed to bys2
(including the terminating null character) into the array pointed to bys1
. If copying takes place between objects that overlap, the behavior is undefined.Returns:
The
strcpy
function returns the value ofs1
.
If you just wanted to replace the first three characters of your string, you can use memcpy()
to copy a specific number of bytes:
memcpy(s1, s2, strlen(s2));
Keep in mind that this will just copy those bytes and nothing more. If s1
isn't already a string of at least the length of s2
, it's unlikely to end well :-)
And just keep one thing in mind re your comment "... resulting in this string: sup\0opo\0".
That is not a string. A string in C (and a legacy string in C++) is defined as a series of characters up to and including the first \0
terminator.
You may well have a series of characters up to the original (now second) \0
but the string is actually shorter than that. This may seem a little pedantic but it's important to understand the definitions.
Your reasoning is correct, and would have easily been confirmed by any decent manual:
The
strcpy()
function copies the string pointed to bysrc
, including the terminating null byte ('\0'
), to the buffer pointed to bydest
.