C++:使用 sizeof 的字符数组的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10735990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:23:39  来源:igfitidea点击:

C++: size of a char array using sizeof

c++arraysstringsizeof

提问by Saad

Look at the following piece of code in C++:

看下面一段 C++ 代码:

char a1[] = {'a','b','c'};
char a2[] = "abc";
cout << sizeof(a1) << endl << sizeof(a2) << endl;

Though sizeof(char)is 1 byte, why does the output show sizeof(a2)as 4 and not 3 (as in case of a1)?

虽然sizeof(char)是 1 个字节,但为什么输出显示sizeof(a2)为 4 而不是 3(如a1)?

回答by Pubby

C-strings contain a null terminator, thus adding a character.

C 字符串包含一个空终止符,因此添加了一个字符。

Essentially this:

本质上是这样的:

char a2[] = {'a','b','c','##代码##'};

回答by Component 10

That's because there's an extra null '\0'character added to the end of the C-string, whereas the first variable, a1is an array of three seperate characters.

这是因为'\0'在 C 字符串的末尾添加了一个额外的空字符,而第一个变量a1是一个由三个单独字符组成的数组。

sizeofwill tell you the byte size of a variable, but prefer strlenif you want the length of a C-string at runtime.

sizeof会告诉您变量的字节大小,但strlen如果您想要运行时 C 字符串的长度,则更喜欢。

回答by miks

For a2, this is a string so it also contains the '\n'

对于 a2,这是一个字符串,因此它还包含 '\n'

Correction, after Ethan & Adam comment, this is not '\n' of course but null terminator which is '\0'

更正,在 Ethan & Adam 评论之后,这当然不是 '\n' 而是空终止符,即 '\0'