In C, the name of an array in a value context is the same as a pointer. That is, if I have an "array of type T
", then it is the same as "pointer to type T
" in a value context. What is a value context? It is basically whenever the value of the object is used. This happens when you pass the name of the object to a function, use the name on the right hand side of an assignment, etc. But in the case above, on the LHS of the expression, it is not used in a value context but "object context", because you are not "reading" the value of the array object, you are assigning to it.
In other words, if you had a pointer (char *msg;
), you could say msg = "something else";
, and it would work, because you are setting the pointer msg
to point to the location that contains the (read-only) string "something else"
. When you have char msg[255];
, you can't say msg = "something else";
because msg
already has a fixed space allocated to it, and it does not make sense to say "this space now points to another space which contains my string". The best thing you can do now is to copy the string from the other location in the location used by msg
. msg
is used in an object context here, and thus doesn't "decay" to a pointer.
For an excellent explanation of the difference, please see C for Smarties: Analyzing expressions.
The solution is to either make msg
a pointer (if your strings are all known at compile-time, or if you don't mind dynamically allocating memory), or to use strcpy()
/strncpy()
(I personally don't like strncpy()
because it might not null-terminate the destination).