Why do I get a seg fault when I use ++ but not when I use '1 +'?
c++, char-pointer, operators, segmentation-fault
Solution
Because you're trying to increment a constant.
char* p = (char*) "hello"; // p is a pointer to a constant string.
cout << ++(*p) << endl; // try to increment (*p), the constant 'h'.
cout << 1 + (*p) << endl; // prints 105 because 1 + 'h' = 105
In other words, the `++` operator attempts to increment the character `p` is pointing to, and then replace the original value with the new one. That's illegal, because `p` points to constant characters. On the other hand, simply adding 1 does not update the original character.
Problem
Please explain why I get the segfault using the ++ operator. What is the difference between explicitly adding 1 and using the ++ operator ? ``` using namespace std; #include <iostream> int main() { char* p = (char*) "hello"; cout << ++(*p) << endl; //segfault cout << 1 + (*p) << endl; // prints 105 because 1 + 'h' = 105 } ```