为什么C中sizeof('a')是4?
可能的重复:
为什么 C 字符文字是整数而不是字符?
#include<stdio.h>
int main(void)
{
char b = 'c';
printf("here size is %zu\n",sizeof('a'));
printf("here size is %zu",sizeof(b));
}
这里的输出是(参见现场演示 这里。)
here size is 4
here size is 1
我不明白为什么 sizeof('a')
是 4 ?
Possible Duplicate:
Why are C character literals ints instead of chars?
#include<stdio.h>
int main(void)
{
char b = 'c';
printf("here size is %zu\n",sizeof('a'));
printf("here size is %zu",sizeof(b));
}
here output is (See live demo here.)
here size is 4
here size is 1
I am not getting why sizeof('a')
is 4 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为在 C 语言中,字符常量(例如 'a')的类型为
int
。有一个关于此主题的 C 常见问题解答:
Because in C character constants, such as 'a' have the type
int
.There's a C FAQ about this suject:
以下是著名的
C
书籍中的著名台词 -C 编程语言
,作者是Kernighan & 。 Ritchie
相对于单引号之间写的字符。写在单引号之间的字符表示一个整数值,等于该字符在机器字符集中的数值。
因此
sizeof('a')
相当于sizeof(int)
The following is the famous line from the famous
C
book -The C programming Language
byKernighan & Ritchie
with respect to a character written between single quotes.A character written between single quotes represents an integer value equal to the numerical value of the character in the machine's character set.
So
sizeof('a')
is equivalent tosizeof(int)
默认情况下,“a”是一个整数,因此您的机器中 int 的大小为 4 个字节。
char 是 1 个字节,因此你得到 1 个字节。
'a' by default is an integer and because of that you get size of int in your machine 4 bytes.
char is 1 bytes and because of this you get 1 bytes.