For starters variable length arrays like char_list
int len = text.length();
char char_list[len + 1];
is not a standard C++ feature. The code will no compile if to use a C++ compiler that does not have its own language extension that allows to use variable length arrays.
In such a case you should dynamically allocate the array
int len = text.length();
char *char_list = new char[len + 1];
also it is a bad idea to use the signed type int
to store an object of the unsigned integer type std::string::size_type
that in general can be too large to be stored in an object of the type int
You could just write using the specifier auto
auto len = text.length();
char *char_list = new char[len + 1];
Nevertheless, the used C string function strcpy
copies characters from source character array in destination character array until the terminating zero character '\0' will not be copied. That is the terminating zero character '\0'
plays role of a sentinel value that is stored in a string along with other characters.
The same way behaves the overloaded operator <<
when its argument has the type char *
.
Without reserving the additional byte for the terminating zero in the character array your program has undefined behavior though it provides for such a simple program the expected result.
You could copy the source object of the type std::string excluding the terminating zero the following way using another string function strncpy or memcpy
int len = text.length();
char char_list[len];
memcpy(char_list, text.c_str(), len );
But in this case you may not use the operator <<. Instead you may write
cout.write( char_list, len ) << endl;