Question

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  

} 
Was it helpful?

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.

OTHER TIPS

You can't modify a C-style string literal. That's what ++(*p) is doing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top