如果我定义如下,
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
这篇关于为什么我不能写入字符串文字而我*可以*写入字符串对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!