The string literal is immutable, as in Java.
String literals are stored in a read-only portion of memory.
For example, if you do something like the following, you will get segfault:
char *ptr = (char *) "hello"; ptr[0] = 'a';
But! You can change the string with s[2] = 'a' , unless the string is declared with the const keyword,
The reason for this is that the = operator for strings is overloaded, takes a string literal as an argument, and then iterates over the string literal, copying each character into a mutable char array.
So, if you are comparing string literals in Java and C, they have the same behavior when it comes to immutability. String objects in Java and C also have the same behavior when it comes to change.
Here is an example showing that the string has a copy:
#include <iostream> #include <string> using namespace std; int main() { const char *ptr = "hello"; string s = ptr; s[0] = 'b'; cout << s << endl; //prints bello cout << ptr << endl; //prints hello return 0; }
source share