Cannot modify char array

newbie picture newbie · Jan 18, 2013 · Viewed 29.1k times · Source

Consider the following code.

char message[]="foo";

void main(void){
    message[] = "bar";
}

Why is there a syntax error in MPLAB IDE v8.63? I am just trying to change the value of character array.

Answer

Yakov Shklarov picture Yakov Shklarov · Jan 18, 2013

Assignments like

message[] = "bar";

or

message = "bar";

are not supported by C.

The reason the initial assignment works is that it's actually array initialization masquerading as assignment. The compiler interprets

char message[]="foo";

as

char message[4] = {'f', 'o', 'o', '\0'};

There is actually no string literal "foo" involved here.

But when you try to

message = "bar";

The "bar" is interpreted as an actual string literal, and not only that, but message is not a modifiable lvalue, ie. you can't assign stuff to it. If you want to modify your array you must do it character by character:

message[0] = 'b';
message[1] = 'a';

etc, or (better) use a library function that does it for you, like strcpy().