Why can#39;t I write to a string literal while I *can* write to a string object?(为什么我不能写入字符串文字而我*可以*写入字符串对象?)
问题描述
如果我定义如下,
char *s1 = "Hello";
为什么我不能做下面这样的事情,
why I can't do something like below,
*s1 = 'w'; // gives segmentation fault ...why???
如果我执行以下操作会怎样,
What if I do something like below,
string s1 = "hello";
我可以做类似下面的事情吗,
Can I do something like below,
*s1 = 'w';
推荐答案
因为 "Hello"
创建了一个 const char[].这会衰减为 const char*
而不是 char*
.在 C++ 中,字符串文字是只读的.您已经创建了一个指向此类文字的指针,并且正在尝试写入.
Because "Hello"
creates a const char[]. This decays to a const char*
not a char*
. In C++ string literals are read-only. You've created a pointer to such a literal and are trying to write to it.
但是当你这样做时
string s1 = "hello";
您将 const char* "hello" 复制到 s1
中.不同之处在于在第一个示例中 s1
指向 只读hello",而在第二个示例中只读hello"被复制到 非常量 s1
,允许您访问复制的字符串中的元素以对它们执行您想要的操作.
You copy the const char* "hello" into s1
. The difference being in the first example s1
points to read-only "hello" and in the second example read-only "hello" is copied into non-const s1
, allowing you to access the elements in the copied string to do what you wish with them.
如果你想对 char* 做同样的事情,你需要为 char 数据分配空间并将 hello 复制到其中
If you want to do the same with a char* you need to allocate space for char data and copy hello into it
char hello[] = "hello"; // creates a char array big enough to hold "hello"
hello[0] = 'w'; // writes to the 0th char in the array
这篇关于为什么我不能写入字符串文字而我*可以*写入字符串对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我不能写入字符串文字而我*可以*写入字符串对象?


- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- C++ 协变模板 2021-01-01