gpt4 book ai didi

c++ - 为什么我不能写入字符串文字,而我*可以*写入字符串对象?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:58:19 27 4
gpt4 key购买 nike

如果我定义如下,

char  *s1 = "Hello";

为什么我不能做下面的事情,

*s1 = 'w'; // gives segmentation fault ...why???

如果我做下面这样的事情会怎样

string s1 = "hello";

我可以像下面那样做吗,

*s1 = 'w'; 

最佳答案

因为 "Hello" 创建了一个 const char[]。这会衰减为 const char* 而不是 char*。在 C++ 中,字符串文字是只读的。您已经创建了一个指向此类文字的指针,并正在尝试写入它。

但是当你这样做的时候

string s1 = "hello";

您将 const char* "hello"复制到 s1 中。区别在于第一个示例 s1 指向只读“hello”,而在第二个示例中,只读“hello”被复制到 非常量 s1,允许您访问复制的字符串中的元素以对它们执行您希望的操作。

如果你想对 char* 做同样的事情,你需要为 char 数据分配空间并将 hello 复制到其中

char hello[] = "hello"; // creates a char array big enough to hold "hello"
hello[0] = 'w'; // writes to the 0th char in the array

关于c++ - 为什么我不能写入字符串文字,而我*可以*写入字符串对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8718740/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com