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';
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because
"Hello"creates a const char[]. This decays to aconst char*not achar*. 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
You copy the const char* “hello” into
s1. The difference being in the first examples1points to read-only “hello” and in the second example read-only “hello” is copied into non-consts1, 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