c++ - 在 C++ 中使用指针更改字符串值

标签 c++ string pointers

<分区>

我在运行以下代码时遇到段错误:-

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/

相关文章:

c++ - 计算数组中的反转次数,C++

python - 如何正确加入尾随或破折号开头的单词? - Python

C++:指针和抽象数组类

c++ - 将opencv Mat创建为二维网格

c++ - 将指向常量指针的指针传递给字节数组的语义冲突

c++ - 清除非字母字符的字符串

c - 结构成员和指针对齐

ios - 无法将类型 'NSDate' 的值分配给类型 'String?' 的值

c - 不知道为什么我会得到 char 数组中第一个元素的输出

c - Scanf - 每个引用的变量 VS 每个引用的参数