0

Why is there a difference between these two array initializations?

char *message = "HELLO";

if(message[0] == 'H'){
    // true
}

Ok, this works. But this doesn't:

char message[6] = "HELLO";

if(message[0] == 'H'){
    // false
}

Aren't they expressing the same thing?

Cœur
  • 37,241
  • 25
  • 195
  • 267
apscience
  • 7,033
  • 11
  • 55
  • 89

2 Answers2

0

"HELLO" has the type const char *. But due to historical reasons this can be considered as a char *.

char messagd[6] is an array of characters on the stack. A different beast.

You need to use strcpy to populate that array

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0

In the first code fragment, message is a pointer to a read-only array of characters. You can modify the pointer (e.g. ++message is fine), but you cannot modify what it points to (message[0] = 'X' invokes undefined behavior).

In the second code fragment, message is an array of characters with an initializer. You cannot modify the variable (++message is invalid), but you can modify the contents of the array (message[0] = 'X' is fine).

Also sizeof(message) is likely to be different.

They behave similarly when you simply access message[0]; that is, either you are wrong about your claimed behavior or your compiler has a very surprising bug.

But they are different things and behave differently in several ways, some of which I just enumerated.

Nemo
  • 70,042
  • 10
  • 116
  • 153