gpt4 book ai didi

c++ - 为什么我在使用++ 时出现段错误,但在使用 '1 +' 时却没有?

转载 作者:太空狗 更新时间:2023-10-29 19:53:08 24 4
gpt4 key购买 nike

请解释为什么我使用++ 运算符会出现段错误。显式加 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

}

最佳答案

因为您要增加一个常量。

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

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

关于c++ - 为什么我在使用++ 时出现段错误,但在使用 '1 +' 时却没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17356570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com