Search code examples
c++initializationc-strings

Why can't char pointers be defined as arrays?


Simple question. I am aware I should just be using std::string, but am curious why this works:

const char* example = "test";

while this results in "too many initializer values" on the second character?

const char* example = {0x74, 0x65, 0x73, 0x74, 0x00};

Shouldn't these two things be exactly equivalent?


Solution

  • The difference is that string literals are arrays all of their own. "test" is used here not as an initializer of an array (a special case where it would be equivalent to { 't', 'e', 's', 't', '\0' }), but the same way as any other value would be.

    In other words, when you use a string literal "test" in your code, the compiler automatically creates something like

    static const char __str_literal0[] = {'t', 'e', 's', 't', '\0'};
    

    and then

    const char *example = "test";
    

    is compiled as if it were

    const char *example = __str_literal0;
    

    i.e. it simply points to the (already existing, static) char array.

    On the other hand, if you try to use an initializer list, the compiler will set the first field of your variable (that's just example itself) to the first value in the initializer list (example = 0x74), and then complain that you have too many initializers in your list.