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
C++: size of a char array using sizeof
提问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, a1
is an array of three seperate characters.
这是因为'\0'
在 C 字符串的末尾添加了一个额外的空字符,而第一个变量a1
是一个由三个单独字符组成的数组。
sizeof
will tell you the byte size of a variable, but prefer strlen
if 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'