I’ve noticed a weird discrepancy in C++.
Say I have this code:
const char myChars[] = "12345";
std::cout << myChars;
The output is: 12345
However, if I then change it to:
const char myChars[] = {'1','2','3','4','5'};
std::cout << myChars;
Then the output is: 12345__SOME_RANDOM_DATA_IN_MEMORY__
Why is it that cout appears to know the length of the first version but not the length of the second version? Also, does cout even know the length?
Thanks.
There is no null terminator in your second example.
would work fine.
Strings literals require a null-terminator to indicate the end of the string.
See this stackoverflow answer for more detailed information: https://stackoverflow.com/a/2037245/507793
As for your first example, when you make a string literal using quotes like
"Hello", that is roughly equivalent to{'H', 'e', 'l', 'l', 'o', 0}, as the null-terminator is implicit when using quotes.