简体   繁体   English

将字符串分配给char数组

[英]Assigning string to the char array

I got confused with string initialization. 我对字符串初始化感到困惑。 I believe that the following: 我相信以下几点:

case1: 情况1:

char s1[100] = { "apple" };

case2: 情况2:

char s1[100];
s1 = "apple";

case1 compiles ok, however, case2 gets error. case1编译正常,但是case2出错。 Compiler says I am trying to assign char[5] to char[100]... Could you clarify the difference between two cases? 编译器说我正在尝试将char [5]分配给char [100] ...您能说明两种情况之间的区别吗?

Explanation of current code 当前代码说明

case 1 is a legal way to initialise s1 , with 'a' going into [0], 'p' into [1] and [2], 'l' into [3], 'e' into [4] and the rest set to 0 (ASCII NUL - see http://en.wikipedia.org/wiki/ASCII ). 情况1是初始化s1的合法方法,其中'a'进入[0],'p'进入[1]和[2],'l'进入[3],'e'进入[4],其余设置为0(ASCII NUL-参见http://en.wikipedia.org/wiki/ASCII )。

case 2 attempts to assign one array to another (of a different size as per the message), which isn't legal in C++. 情况2尝试将一个数组分配给另一个数组(根据消息大小不同),这在C ++中是不合法的。 You should use strcpy(s1, "apple") to do this, though it differs slightly in behaviour: it will only set s1[5] to 0/NUL, with [6] onwards unaffected (if s1 is on the stack or heap they'll be uninitialised and reading from them will be undefined behaviour). 您应该使用strcpy(s1, "apple")来执行此操作,尽管它的行为略有不同:它只会将s1[5]设置为0 / NUL,而[6]以后则不受影响(如果s1在堆栈或堆中)它们将不会被初始化,并且从它们中读取将是不确定的行为)。 Most things you'd want to do with s1 won't benefit from initialisation of [6] onwards.... 您想对s1大多数操作都不会从[6]开始的初始化中受益。

An intuitive alternative: `std::string` 一个直观的选择:`std :: string`

Perhaps the best approach is to switch to std::string , which works more intuitively (you'll have to #include <string> atop your program). 也许最好的方法是切换到std::string ,该方法更直观(您必须在程序顶部#include <string> )。 The syntax for case 1 will be slightly different though: either std::string s1 = "apple"; 但是,情况1的语法会稍有不同: std::string s1 = "apple"; , or - if you have a C++11 compiler - std::string s1 { "apple" }; ,或者-如果您使用的是C ++ 11编译器std::string s1 { "apple" }; .

Writable buffers versus pointers to string literals 可写缓冲区与指向字符串文字的指针

Note too that in your question, char s1[100] creates an array of 100 characters that you can read and write to, and you're then copying from a read-only ("const") string literal into that writable buffer. 还要注意,在您的问题中, char s1[100]创建一个可以读取和写入100个字符的数组,然后将其从只读(“ const”)字符串文字复制到该可写缓冲区中。 If you just want to keep track of the text (eg that it's "apple" as opposed to say "orange" which might be copied into s1 later) without needing to modify the text further, you can use a const char* to store the address of the string literal: 如果您只是想跟踪文本(例如,它是“苹果”而不是“橙色”,以后可能会复制到s1 )而无需进一步修改文本,则可以使用const char*存储该文本。字符串文字的地址:

const char* p_s1 = "apple";
if (f()) p_s1 = "orange";
std::cout << "go eat an " << p_s1 << '\n';

As an example of the const nature of string literals, with the const char* p_s1 above you can't modify the pointed-to string literals as in: 作为字符串文字的const性质的示例,使用上面的const char* p_s1 ,您不能像以下那样修改指向的字符串文字:

#include <cctype>
...
p_s1[0] = std::toupper(p_s1[0]);   // oops! p_s1[0] inside string literal - mustn't write

Whereas if you'd stuck with char s1[100]; 而如果您坚持使用char s1[100]; you could do: 你可以做:

s1[0] = std::toupper(s1[0]);       // ok

The buit-in arrays (so called raw arrays) do not support direct assignment. 内置数组(所谓的原始数组)不支持直接分配。

Your case 1 is not assignment: it's initialization. 您的情况1不是指派:它是初始化。

The standard library offers std::array which essentially wraps a raw array in a struct , and thus is assignable. 标准库提供了std::array ,它实际上将原始数组包装在struct ,因此是可分配的。

However, for the apparent purpose of your code an array would be the wrong choice. 但是,出于代码的明显目的,数组将是错误的选择。

Instead use a std::string , which supports both initialization from and assignment of a string literal. 而是使用std::string ,它支持字符串文字的初始化和赋值。


Example (include <string> ): 示例(包括<string> ):

using std::string;
string s1 = "apple";
string s2;

s2 = apple;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM