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

2024-05-12C/C++开发问题
3

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

问题描述

如果我定义如下,

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

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

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6