Search code examples
cstringpointersstring-literals

Unexpected C string definition behaviour


As far as I know the below code should not work. Yet, somehow this is OK on my compiler. Please could someone explain.

int main()
{
    char *string;
    string = "Goo";
}

Solution

  • As far as I know the below code should not work

    I'm afraid, your information is wrong.

    char *string;
    string = "Goo";
    

    is perfectly valid. This is basically,

    1. Define a char pointer string.
    2. Put the base address of the string literal "Goo" into string.

    However, instead of being a char pointer, if string would have been an array, then this would not have been possible as array's cannot be assigned (except definition time though brace enclosed list).