<分区>
我在运行以下代码时遇到段错误:-
char *p ="Hello";
*p = 'M';
我打算将字符串 "Hello"
的第一个字符替换为 'M'
。但是我遇到了段错误。可能是什么原因?
<分区>
我在运行以下代码时遇到段错误:-
char *p ="Hello";
*p = 'M';
我打算将字符串 "Hello"
的第一个字符替换为 'M'
。但是我遇到了段错误。可能是什么原因?
最佳答案
这是未定义的行为。为了与旧的 C 代码兼容,C++ 编译器允许您将非 const
指针指向字符串文字(例如您的 "Hello"
),但您不能写通他们便携。
最好使用:
const char* p = "Hello"; // if you really need a pointer, probably so you
// can move it within the text, point it at other
// text, set it to a NULL sentinel after use...
const char[] hello = "Hello"; // if you're really only interested in the text
关于c++ - 在 C++ 中使用指针更改字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21674641/