Consider the following code.
int main(void) { char * test = "abcdefghijklmnopqrstuvwxyz"; test[5] = 'x'; printf("%s\n", test); return EXIT_SUCCESS; }
In my opinion, this should print abcdexghij. However, it just terminates without printing anything.
int main(void) { char * test = "abcdefghijklmnopqrstuvwxyz"; printf("%s\n", test); return EXIT_SUCCESS; }
This however, works just fine, so did I misunderstand the concept of manipulating C strings or something? In case it is important, I'm running Mac OS X 10.6 and it is a 32-bit binary I'm compiling.
No, you cannot modify it, as the string can be stored in read-only memory. If you want to modify it, you can use an array instead e.g. char a[] = "This is a string"; Or alternately, you could allocate memory using malloc e.g.
In general, C strings are mutable. The C++ language has its own string class. It is mutable. In both C and C++, string constants (declared with the const qualifier) are immutable, but you can easily “cast away” the const qualifier, so the immutability is weakly enforced.
The behavior is undefined if a program attempts to modify any portion of a string literal. Modifying a string literal frequently results in an access violation because string literals are typically stored in read-only memory.
A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string.
Char pointers defined with an initialization value go into a read-only segment. To make them modifiable, you either need to create them on the heap (e.g. with new
operator or malloc()
function) or define them as an array.
Not modifiable:
char * foo = "abc";
Modifiable:
char foo[] = "abc";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With