-2
Why is this substitution of a character within a string not working?
int main(){
char *armazena = "XXX", letra = 'a';
letra = armazena[2];
*(armazena+1) = 'a';
printf("%c", armazena[1]);
return 0;
}
-2
Why is this substitution of a character within a string not working?
int main(){
char *armazena = "XXX", letra = 'a';
letra = armazena[2];
*(armazena+1) = 'a';
printf("%c", armazena[1]);
return 0;
}
2
As already stated in the comments, strings declared as char *string = ""
cannot be modified. But why?
The reason it can’t be modified is because you created a pointer referencing a string static, i.e., was created at compile time. This string will be stored in the binaries of your compiled program, not in the context of its function (or memory stack).
Not only that, but your program is optimized so that all identical static strings point to the same memory address.
For example, in the following code:
char *str1 = "XXX";
char *str2 = "XXX";
str1
and str2
are not just identical strings, they are exactly the same string in the memory address, which means that if you modify str1
, would be modifying str2
.
This opens the possibility of several problems with strings being declared in different files being accidentally modified. For this reason the compiler will try to prevent you from modifying such strings, and you should also avoid doing so, even if you can circumvent the check.
How to create a mutable string
Any non-static string can be modified, be it declared in the memory stack:
char str[] = "XXX";
str[0] = 'Z';
printf("%s", str);
Or in the heap:
char *str = malloc(4); // reservo espaço para 4 caracteres no heap
strcpy(str, "XXX"); // copio o conteúdo da string estática para o heap
str[0] = 'Z';
printf("%s", str);
free(str);
And what would be the way to change a character of a string that is passed by an array within a function?
@Higorluiz, see if editing helps you.
Browser other questions tagged c
You are not signed in. Login or sign up in order to post.
char *armazena = "XXX"
creates a string readonly (cannot be modified), hence the error. Switch tochar armazena[] = "XXX"
. See more on https://stackoverflow.com/q/7564033– hkotsubo