Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I change char array later?

Tags:

c

string

char myArray[6]="Hello"; //declaring and initializing char array

printf("\n%s", myArray); //prints Hello
myArray="World";  //Compiler says"Error expression must a modifiable lvalue

Why can't I change myArray later? I did not declare it as const modifier.

like image 507
Lyrk Avatar asked Nov 30 '22 12:11

Lyrk


1 Answers

When you write char myArray[6]="Hello"; you are allocating 6 chars on the stack (including a null-terminator).

Yes you can change individual elements; e.g. myArray[4] = '\0' will transform your string to "Hell" (as far as the C library string functions are concerned), but you can't redefine the array itself as that would ruin the stack.

Note that [const] char* myArray = "Hello"; is an entirely different beast: that is read-only memory and any changes to that string is undefined behaviour.

like image 87
Bathsheba Avatar answered Dec 05 '22 01:12

Bathsheba