Unexpected C string definition behaviour

101 views Asked by At

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";
}
1

There are 1 answers

12
Sourav Ghosh On BEST ANSWER

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).