I am brushing up on my C++ and stumbled across a curious behavior in regards to strings, character arrays, and the null character ('\0'
). The following code:
#include <iostream>
using namespace std;
int main() {
cout << "hello\0there"[6] << endl;
char word [] = "hello\0there";
cout << word[6] << endl;
string word2 = "hello\0there";
cout << word2[6] << endl;
return 0;
}
produces the output:
> t
> t
>
What is going on behind the scenes? Why does the string literal and the declared char array store the 't'
at index 6 (after the internal '\0'
), but the declared string does not?