C和C++中的字符大小是多少?据我所知,char的大小在C和C++中都是1个字节.
#include <stdio.h>
int main()
{
printf("Size of char : %d\n", sizeof(char));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
#include <iostream>
int main()
{
std::cout << "Size of char : " << sizeof(char) << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
没有惊喜,它们都给出了输出: 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;
}
Run Code Online (Sandbox Code Playgroud)
Size of char …Run Code Online (Sandbox Code Playgroud) 我试过了
printf("%d, %d\n", sizeof(char), sizeof('c'));
得到1,4作为输出.如果一个角色的大小是一个,为什么'c'给我4?我想这是因为它是一个整数.所以,当我这样做时,是否会char ch = 'c';发生隐式转换,在它被分配给char变量时,从4字节值到1字节值?