Reputation: 2000
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.
Upvotes: 5
Views: 5286
Reputation: 13461
You cannot assign naked arrays in C. However you can assign pointers:
char const *myPtr = "Hello";
myPtr = "World";
Or you can assign to the elements of an array:
char myArray[6] = "Hello";
myArray[0] = 'W';
strcpy(myArray, "World");
Upvotes: 2
Reputation: 399
Well myArray
is the name of the array which you cannot modify. It is illegal to assign a value to it.
Arrays in C are non-modifiable lvalues
. There are no operations in C that can modify the array itself (only individual elements can be modifiable).
Well myArray
is of size 6 and hence care must be taken during strcpy
.
strcpy(myArray,"World")
as it would result in overflow if the source's string length is more than the destination's (6 in this case).
A arrays in C are non-modifiable lvalues. There are no operations in C that can modify the array itself (only individual elements can be modifiable). A possible and safe method would be
char *ptr = "Hello";
If you want to change
ptr = strdup("World");
NOTE:
Make sure that you free(ptr)
at the end otherwise it would result in memory leak.
Upvotes: 2
Reputation: 234715
When you write char myArray[6]="Hello";
you are allocating 6 char
s 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.
Upvotes: 6
Reputation: 732
You can't assign strings to variables in C except in initializations. Use the strcpy() function to change values of string variables in C.
Upvotes: 2
Reputation: 122403
Because the name of an array cannot be modified, just use strcpy
:
strcpy(myArray, "World");
Upvotes: 3
Reputation: 206546
Array is a non modifiable lvalue. So you cannot modify it.
If you wish to modify the contents of the array, use strcpy
.
Upvotes: 4
Reputation: 409216
You can't assign to an array (except when initializing it in its declaration. Instead you have to copy to it. This you do using strcpy
.
But be careful so you don't copy more than five characters to the array, as that's the longest string it can contain. And using strncpy
in this case may be dangerous, as it may not add the terminating '\0'
character if the source string is to long.
Upvotes: 2