为什么C中sizeof('a')是4?

发布于 2024-12-23 04:25:09 字数 594 浏览 4 评论 0原文

可能的重复:
为什么 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

分开我的手 2024-12-30 04:25:09

因为在 C 语言中,字符常量(例如 'a')的类型为 int

有一个关于此主题的 C 常见问题解答

也许令人惊讶的是,C 中的字符常量是 int 类型,因此
sizeof('a') 是 sizeof(int) (尽管这是 C++ 的另一个领域
不同)。

Because in C character constants, such as 'a' have the type int.

There's a C FAQ about this suject:

Perhaps surprisingly, character constants in C are of type int, so
sizeof('a') is sizeof(int) (though this is another area where C++
differs).

野稚 2024-12-30 04:25:09

以下是著名的 C 书籍中的著名台词 - C 编程语言,作者是 Kernighan & 。 Ritchie 相对于单引号之间写的字符。

写在单引号之间的字符表示一个整数值,等于该字符在机器字符集中的数值。

因此sizeof('a')相当于sizeof(int)

The following is the famous line from the famous C book - The C programming Language by Kernighan & 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 to sizeof(int)

倾城花音 2024-12-30 04:25:09

默认情况下,“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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文