C语言变量所占字节数整理:
变量的基本类型包括:字符型、整型、长整型、浮点型。
每个变量在每个编译器所占的字节数不同,《the C Programming language》是这样说的:
Each compiler is free to choose appropriate sizes for its own hardware, subject only to the restriction that ints are at least 16bits,longs are at least 32bits, and short is no longer than int, which is no longer than long .
也就意味着编译器可以根据自身的硬件选择合适的大小,约束条件是:short和int至少为16位;并且short的长度不得大于int ; int的长度不得大于long.
总结即为:
1 sizeof(short int) <= sizeof(int)
2 sizeof(int) <= sizeof(long int)
3 short int至少应为16位(2字节)
4 long int至少应为32位。
unsigned 为无符号。**
注意:指针类型存储的是**所指向变量的地址,32位的编译器需要32bit(即4个字节),64位的机器需要需要64bit(即8个字节).
当下主流的编译器是32位和64位。下面列举32位和64位编译器各个类型变量所占的字节数:
char存储大小1字节,值范围-128~127;
unsigned char存储大小1字节,值范围0~255;
short存储大小2字节,值范围-32768~32767;
unsigned short存储大小2字节,值范围0~65535;
sizeof(type)得到对象或类型的存储字节大小。
例子:32位的编译器下
Sizeof(int) = 4 ;sizeof(char) = 1 ;sizeof(*char)= 4 ; sizeof(long int ) = 4 ;
Void main
{
double i;
int j;
char n;
}
以上函数的sizeof= 16 ;对齐原则,double是8个字节,int是4个字节,char是一个字节,补3个对齐;所以一共16个字节。