C 和 C++ 中字符的大小是多少?据我所知,char 的大小在 C 和 C++ 中都是 1 字节。
In C:
#include <stdio.h>
int main()
{
printf("Size of char : %d\n", sizeof(char));
return 0;
}
In C++:
#include <iostream>
int main()
{
std::cout << "Size of char : " << sizeof(char) << "\n";
return 0;
}
不出意外,它们都给出了输出:Size of char : 1
现在我们知道字符表示为'a'
,'b'
,'c'
,'|'
,...所以我只是将上面的代码修改为这些:
在 C 中:
#include <stdio.h>
int main()
{
char a = 'a';
printf("Size of char : %d\n", sizeof(a));
printf("Size of char : %d\n", sizeof('a'));
return 0;
}
Output:
Size of char : 1
Size of char : 4
在 C++ 中:
#include <iostream>
int main()
{
char a = 'a';
std::cout << "Size of char : " << sizeof(a) << "\n";
std::cout << "Size of char : " << sizeof('a') << "\n";
return 0;
}
Output:
Size of char : 1
Size of char : 1
为什么 sizeof('a')
在 C 和 C++ 中返回不同的值?
最佳答案
在 C 中,constant 像 'a'
这样的字符类型实际上是一个 int
,大小为 4(或其他依赖于实现的值)。在 C++ 中,类型是 char
,大小为 1。这是两种语言之间的许多小差异之一。
https://stackoverflow.com/questions/2172943/