“sizeof”的意外结果字符串
为什么 sizeof 在以下情况下会打印不同的值:
printf("%d",sizeof("ab")); //print 3
char* t="ab";
printf("%d",sizeof(t)); //print 4
在第一种情况下,我有 2 个字符... sizeof
不应该打印 2 吗?因为它们是2个字节?
Why would sizeof in the following cases print different values:
printf("%d",sizeof("ab")); //print 3
char* t="ab";
printf("%d",sizeof(t)); //print 4
In the first case I have 2 characters... Shouldn't sizeof
print 2? Because they are 2 bytes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
“ab”在内存中看起来像
'a' 'b' '\0'
而
t
是一个指针,所以大小是 4。"ab" in memory looks like
'a' 'b' '\0'
While
t
is a pointer, so size is 4.t
是指向包含"ab"
的数组的指针。它的大小是指针的大小。"ab"
是一个包含"ab"
的数组。它的大小就是该数组的大小,它是三个字符,因为您必须考虑空终止符。数组不是指针。
t
is a pointer to an array containing"ab"
. Its size is the size of a pointer."ab"
is an array containing"ab"
. Its size is the size of that array, which is three characters because you have to account for the null terminator.Arrays are not pointers.
因为在第一种情况下,您要求的是数组的大小。第二次你询问指针的大小。
Because in the first case you are asking for the sizeof an array. The second time you are asking for the size of a pointer.
字符串文字是 char 数组,而不是 char *。
A string literal is a char array, not a char *.
字符串文字
"ab"
的类型是const char(&)[3]
。所以
sizeof("ab") = sizeof(const char(&)[3]) = sizeof(char) * 3
在你的机器上是 3。在另一种情况下,
t
只是一个指针。所以
sizeof(t) = sizeof(void*)
在你的机器上是 4 个字节。--
注意:
如果您在
"ab"
前面加上L
,并将其设为L"ab"
,则,字符串文字
L"ab"
的类型为const wchar_t(&)[3]
。所以
sizeof(L"ab") = sizeof(const wchar_t(&)[3]) = sizeof(wchar_t) * 3
在 ideone 上是 12:http://ideone.com/IT7aR
所以这是因为使用 GCC 编译的 ideone 上的
sizeof(wchar_t) = 4
!The type of the string literal
"ab"
isconst char(&)[3]
.So
sizeof("ab") = sizeof(const char(&)[3]) = sizeof(char) * 3
which is 3 on your machine.And in the other case,
t
is just a pointer.So
sizeof(t) = sizeof(void*)
which is 4 bytes on your machine.--
Note:
If you prepend
"ab"
withL
, and make itL"ab"
, then,The type of the string literal
L"ab"
isconst wchar_t(&)[3]
.So
sizeof(L"ab") = sizeof(const wchar_t(&)[3]) = sizeof(wchar_t) * 3
which is 12 on ideone:http://ideone.com/IT7aR
So that is because
sizeof(wchar_t) = 4
on ideone which is using GCC to compile!