The function std::ostream::operator<<
that you are trying to use in the last line of the main will take your char
array as a pointer and will print every char
until the null sentinel character is found (the character is \0
).
This sentinel character is generally generated for you in statements where a C-string literal is defined:
char s[] = "123";
In the above example sizeof(s)
is 4
because the actual characters stored are:
'1', '2', '3', '\0'
The last character is fundamental in tasks that require to loop on every char of a const char*
string, because the condition for the loop to terminate, is that the \0
must be read.
In your example the "junk" that you see are the bytes following the 0
char byte in the memory (interpreted as char
). This behavior is clearly undefined and can potentially lead the program to crash.
One solution is to obviously add the \0
char at the end of the char array (of course fixing the size).
The best solution, though, is to never use const char*
for strings at all. You are correctly using std::string
in your example, which will prevent this kind of problems and many others.
If you ever need a const char*
(for C APIs for example) you can always use std::string::c_str
and retrieve the C string version of the std::string
.
Your example could be rewritten to:
int main(int, char*[]) {
std::string ss = "1234567890";
const char* data = ss.c_str();
std::cout << data << std::endl;
}
(in this particular instance, a version of std::ostream::operator<<
that takes a std::string
is already defined, so you don't even need data
at all)