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

If I define something like below,

char *s1 = "Hello"; 

why can't I do something like below

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

What if I do something like below

 string s1 = "hello"; 

Is it possible to do something like below

 *s1 = 'w'; 
+4
source share
4 answers

Because "Hello" creates const char []. It splits into a const char* not a char* . In C ++, string literals are read-only. You have created a pointer to such a literal and are trying to write to it.

But when you do

 string s1 = "hello"; 

You copy const char * "hello" to s1 . The difference in the first example s1 indicates read-only “hello”, and in the second example “read-only welcome” is copied to non const s1 , allowing you to access the elements in the copied line to do what you want with them .

If you want to do the same with char *, you need to allocate space for char data and copy hi to it

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

usually allocated in a read-only data segment.

+2
source

Because Hello is in read-only memory. Your signature must be

 const char* s1 = "Hello"; 

If you need a mutable buffer, declare s1 as char[] . std::string overloads operator [] , so you can index it, i.e. s1[index] = 'w' .

+1
source

Time to confuse questions:

 char s0[] = "Hello"; s0[0] = 'w'; 

This is absolutely true! Of course, this does not answer the original question, so we go: string literals are created in read-only memory. That is, their type is char const[n] , where n is the size of the string (including the terminating null character, ie n == 6 for the string literal "Hello" . But why, oh why this type can be used to initialize a char const* ? The answer is just backward compatibility, correspondingly compatible with the [old] C code: by the time const did this in the language, there are a lot of places already char* initialized with string literals.Any decent compiler should warn of this abuse, however .

0
source

Source: https://habr.com/ru/post/1389150/


All Articles