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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With