Use of null character in strings (C++)

ewok picture ewok · Jul 20, 2012 · Viewed 24.5k times · Source

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?

Answer

sean picture sean · Jul 20, 2012

From what I remember, the first two are in essence just an array and the way a string is printed is to continue to print until a \0 is encounterd. Thus in the first two examples you start at the point offset of the 6th character in the string, but in your case you are printing out the 6th character which is t.

What happens with the string class is that it makes a copy of the string into it's own internal buffer and does so by copying the string from the start of the array up to the first \0 it finds. Thus the t is not stored because it comes after the first \0.