当我使用++时为什么会出现seg错误但是当我使用'1 +'时却没有?

Kac*_*aye 3 c++ operators segmentation-fault char-pointer

请解释为什么我使用++运算符获得segfault.显式添加1和使用++运算符有什么区别?

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  

} 
Run Code Online (Sandbox Code Playgroud)

Ada*_*iss 8

因为你试图增加常数.

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
Run Code Online (Sandbox Code Playgroud)

换句话说,++运算符尝试增加字符p指向的值,然后用新值替换原始值.这是非法的,因为p指向恒定的字符.另一方面,简单地添加1不会更新原始字符.