Why can’t I write to a string literal while I *can* write to a string object?

Because "Hello" creates a const char[]. This decays to a const char* not a char*. In C++ string literals are read-only. You’ve created a pointer to such a literal and are trying to write to it.

But when you do

string s1 = "hello";

You copy the const char* “hello” into s1. The difference being in the first example s1 points to read-only “hello” and in the second example read-only “hello” is copied into non-const s1, allowing you to access the elements in the copied string to do what you wish with them.

If you want to do the same with a char* you need to allocate space for char data and copy hello into it

char hello[] = "hello"; // creates a char array big enough to hold "hello"
hello[0] = 'w';           //  writes to the 0th char in the array

Leave a Comment