C语言数据类型
使用sizeof计算各数据类型占用内存大小
#include<stdio.h>
int main()
{
typedef struct {
int a ;
char b;
int c;
}struct_test_t;
typedef enum{
test1 =1,
test2,
test3,
test4,
test5
}enum_test;
typedef enum{
test11 =100000000000,
test22,
test33,
test44,
test55
}enum_test2;
typedef union{
char a;
short b;
int c;
}union_test;
char a[10] = {0};
short b[10] = {0};
int c[10] = {0};
printf("sizeof(char):%d \n",sizeof(char));
printf("sizeof(unsigned char):%d \n",sizeof(unsigned char));
printf("sizeof(short):%d \n",sizeof(short));
printf("sizeof(unsigned short):%d \n",sizeof(unsigned short));
printf("sizeof(int):%d \n",sizeof(int));
printf("sizeof(unsigned int):%d \n",sizeof(unsigned int));
printf("sizeof(long):%d \n",sizeof(long));
printf("sizeof(unsigned long):%d \n",sizeof(unsigned long));
printf("sizeof(float):%d \n",sizeof(float));
printf("sizeof(double):%d \n",sizeof(double));
printf("sizeof(char *):%d \n",sizeof(char *));
printf("sizeof(struct_test_t *):%d \n",sizeof(struct_test_t *));
printf("sizeof(struct_test_t):%d \n",sizeof(struct_test_t));
printf("sizeof(enum_test):%d \n",sizeof(enum_test));
printf("sizeof(enum_test2):%d \n",sizeof(enum_test2));
printf("sizeof(union_test):%d \n",sizeof(union_test));
printf("sizeof(char a[10]):%d \n",sizeof(a));
printf("sizeof(short b[10]):%d \n",sizeof(b));
printf("sizeof(int c[10]):%d \n",sizeof(c));
return 0 ;
}
运行结果
32位编译运算结果如下
sizeof(char):1
sizeof(unsigned char):1
sizeof(short):2
sizeof(unsigned short):2
sizeof(int):4
sizeof(unsigned int):4
sizeof(long):4
sizeof(unsigned long):4
sizeof(float):4
sizeof(double):8
sizeof(char *):4
sizeof(struct_test_t *):4
sizeof(struct_test_t):12
sizeof(enum_test):4
sizeof(enum_test2):8
sizeof(union_test):4
sizeof(char a[10]):10
sizeof(short b[10]):20
sizeof(int c[10]):40
64位编译运算结果如下
sizeof(char):1
sizeof(unsigned char):1
sizeof(short):2
sizeof(unsigned short):2
sizeof(int):4
sizeof(unsigned int):4
sizeof(long):8
sizeof(unsigned long):8
sizeof(float):4
sizeof(double):8
sizeof(char *):8
sizeof(struct_test_t *):8
sizeof(struct_test_t):12
sizeof(enum_test):4
sizeof(enum_test2):8
sizeof(union_test):4
sizeof(char a[10]):10
sizeof(short b[10]):20
sizeof(int c[10]):40
总结
我们一般在32/64位编译器上使用sizeof计算各数据类型占用内存大小,可以得出下面结论:
char 占1字节
short / short int 占2字节
int 占4字节
long / long int //32位机编译器占4字节,64位编译器占8字节。
float 占4字节
double 占8字节
指针类型由编译器决定 //32位机编译器占4字节,64位编译器占8字节。
枚举类型默认int大小,test11 =1,则占用4字节。如果枚举成员test11 =100000000000,则占用8字节。
结构体占用大小由成员共同决定。 (参考:另一篇blog《C语言结构体对齐问题》 https://blog.youkuaiyun.com/j_learn/article/details/89813066)
联合体占用大小类似结构体。
数组由数据类型*数组成员个数决定。
要知道数据类型的大小,方法就是使用sizeof亲测!!!