Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot modify char array

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.

like image 371
newbie Avatar asked Jan 18 '13 09:01

newbie


2 Answers

You cannot use character array like that after declaration. If you want to assign new value to your character array, you can do it like this: -

strcpy(message, "bar");
like image 94
Rohit Jain Avatar answered Sep 29 '22 00:09

Rohit Jain


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

like image 29
Yakov Shklarov Avatar answered Sep 29 '22 02:09

Yakov Shklarov