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

编程入门 行业动态 更新时间:2024-10-10 04:22:32
本文介绍了为什么我不能写入字符串文字而我*可以*写入字符串对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我定义如下,

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

更多推荐

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

本文发布于:2023-11-24 14:24:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1625572.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   而我   对象   文字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!