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)
因为你试图增加常数.
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不会更新原始字符.
| 归档时间: |
|
| 查看次数: |
90 次 |
| 最近记录: |