Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

stl

If i define something like below,

char  *s1 = "Hello";

why I can't do something like below,

*s1 = 'w'; // gives segmentation fault ...why???

What if I do something like below,

string s1 = "hello";

Can I do something like below,

*s1 = 'w'; 
like image 531
user882196 Avatar asked Jan 03 '12 21:01

user882196


1 Answers

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
like image 90
Doug T. Avatar answered Nov 03 '22 01:11

Doug T.