Good. Do you understand the (minute) difference of the solutions?
Recap:
1 2 3
|
char foo[] = {'w', 'o', 'r', 'l', 'd' };
char bar[] = "world";
std:.string gaz = "world";
|
The foo is an array of characters.
The bar is an array of characters.
The gaz is a std::string object.
The foo is initialized with an array of characters. The initilizer array has 5 characters and thus the foo has 5 elements.
The bar is initialized with an array of characters. The initilizer array has 6 characters and thus the foo has 6 elements.
The gaz is initialized with an array of characters. The initilizer array has 6 characters but string stores only the first 5 non-null elements.
1 2 3
|
std::cout << gaz;
std::cout << bar;
std::cout << foo;
|
The string gaz has its own output operator that correctly outputs the 5 characters of "world".
The bar outputs exactly "world", because there is a null character after the 'd'.
We have no idea what prints after the 'd' of foo, because those memory locations can have anything.
In other words, the
"world"
is a shorthand for writing
{'w', 'o', 'r', 'l', 'd', 0 }
The array used in
Shadowwolf's program did not include a terminating null. Hence, it does print random characters after the hello.
The use of
std::string
cunningly avoids many issues that one encounters with plain array.