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.
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.
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");
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().
you can do that only in the initialisation when you declare the char array
message[] = "bar";
You can not do it in your code
To modify it you can use strcpy
from <string.h>
strcpy(message, "bar");
You cant change the character array like this . If you want to change the value of character array then you have to change it by modifying single character or you can use
strcpy(message,"bar");
char message[]="foo";
This statement cause compiler to create memory space of 4 char variable.Starting address of this memory cluster is pointer value of message
. address of message
is unchangeable, you cannot change the address where it points . In this case, your only chance is changing the data pointed by message
.
char* message="foo"
In this time, memory is created to store the address of pointer, so the address where message
point can change during execution. Then you can safely do message="bar"