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
这篇关于为什么我不能写入字符串文字而我*可以*写入字符串对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我不能写入字符串文字而我*可以*写入字符串对象?


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30