What is a good way of creating a constant string in C? A string that cannot be mutated by doing character assignment to one of its indexed location. And a string that cannot be replaced by another string in later execution after initialization.
I tried both char* and char[] in the following code. I tried them with and without the "const" keywords. The outcome is very bizarre.
The following is my code:
#include <stdio.h>
main() {
char a []= "abc" "def";
char* b = "abcdef";
const char c [] = "abcdef";
const char* d = "abcdef";
a[1] = 'y';
b[1] = 'y';
c[1] = 'y';
d[1] = 'y';
printf("%s %s %s %s \n", a, b, c, d);
a = "overwrited";
b = "overwrited";
c = "overwrited";
d = "overwrited";
printf("%s %s %s %s \n", a, b, c, d);
}
The result is that In the first printf, all a, b, c, d can be mutated; but c and d appear warnings that "assignment of read-only location". In the second printf, both a and c return error. But b and d are smoothly replaced by another string and become "ovewrited".
I am very confused by this result that it seems like "const" keyword doesn't have the effect on doing string assignment; but it has effect on indexed character mutation. And char[] and char* show different behaviours as well. Could someone explain to me the mechanism behind this?