char
arrays are often used for null-terminated strings, but not always.
When you write
const char* str = "Hello";
then str
is a pointer to the first element of a const char[6]
. 5
for the characters, and the rules of the language make sure that there is room for the terminating \0
.
On the other hand, sometimes a char
array is just that: An array of characters. When you write
char sentence[] ={'H','e','l','l','o'};
Then sentence
is an array of only 5
char
s. It is not a null-terminated string.
This two worlds (general char
array / null-terminated strings) clash when you call
std::cout << sentence << std::endl;
because the operator<<
overload does expect a null-terminated string. Because sentence
does not point to a null-terminated string, your code has undefined behavior.
If you want sentence
to be a string, make it one:
char sentence[] = {'H','e','l','l','o','\0'};
Or treat it like a plain array of characters:
for (const auto& c : sentence) {
std::cout << c;
}