为什么我不能写一个字符串字面量,而我*可以*写一个字符串对象? [英] Why can't I write to a string literal while I *can* write to a string object?

查看:169
本文介绍了为什么我不能写一个字符串字面量,而我*可以*写一个字符串对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我定义如下,

  char * s1 =Hello 

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

  * s1 ='w'; //给分段错误...为什么? 

如果我执行下面的操作该怎么办,

  string s1 =hello; 

我可以这样做,

  * s1 ='w'; 

解决方案

因为Hello / code>创建一个常量char []。这会衰减到 const char * 而不是 char * 。在C ++中,字符串文字是只读的。



但是当你这样做

  string s1 =hello; 

您将const char *hello复制到 s1 。区别在于第一个示例 s1 指向只读hello,第二个示例只读hello复制到非常量 s1 中,允许您访问复制的字符串中的元素,以做他们想要的。



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

  char hello [] =hello; //创建一个足够大的char数组来保存hello
hello [0] ='w'; //写入数组中的第0个字符


If i define something like below,

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'; 

解决方案

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.

But when you do

string s1 = "hello";

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.

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

这篇关于为什么我不能写一个字符串字面量,而我*可以*写一个字符串对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆