执行结果如下:本示例的测试环境是:
操作系统:CentOS(Linux 192 2.6.18-348.6.1.el5 x86_64 GNU/Linux)
编译器 :cc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-54)
测试代码如下:
1 #include <stdio.h> 2 #include <malloc.h> 3 4 typedef struct point 5 { 6 int x; 7 int y; 8 char *description; 9 char *message; 10 } Point; 11 12 typedef union job 13 { 14 char *name; 15 int salary; 16 int worker_no; 17 18 19 } Job; 20 21 main() 22 { 23 char* arrays[] = { "Abc", "abc", "1bc", "123" }; 24 25 int n = 0; 26 printf("int sizeof(%d) = %d\n",n, sizeof(n) ); 27 28 unsigned int m = 0; 29 printf("unsigned sizeof(%u) = %d\n",m,sizeof(m)); 30 31 char c = ‘\0‘; 32 printf("char sizeof(%c) = %d\n", c,sizeof(c)); 33 34 long lo = 0; 35 printf("long sizeof(%ld) = %d\n", lo, sizeof(lo) ); 36 37 unsigned long ulo = 0; 38 printf("unsigned long sizeof(%ld) = %d\n", ulo, sizeof(ulo) ); 39 40 char *pString = "Hello World"; 41 42 int iInt = 12; 43 int *pInt = &iInt; 44 45 printf("pointer size(*pInt) = %d\n", sizeof(pInt) ); 46 printf("pointer sizeof(*p) = %d\n", sizeof(pString)); 47 printf("pointer sizeof(arrays)= %d\n", sizeof(*arrays)); 48 49 int length = sizeof(arrays)/sizeof(*arrays); 50 51 printf("arrays.length = %d\n", length ); 52 53 int i; 54 for( i = 0 ; i<length; i++) 55 { 56 printf("arrays[%d] = %s\n", i, *(arrays + i) ); 57 } 58 59 Point *p; 60 p = malloc(sizeof(struct point)); 61 p->x = 100; 62 p->y = 100; 63 p->description = pString; 64 65 printf("point x = %d, y = %d, description = %s\n", p->x, p->y, p->description ); 66 printf("struct sizeof(struct point) = %d\n", sizeof(struct point) ); 67 printf("struct pointer sizeof(p) = %d\n", sizeof(p) ); 68 69 printf("union sizeof(job) = %d\n", sizeof(Job) ); 70 71 char name[10]; 72 printf("char arrays sizeof(name) = %d\n", sizeof(name)); 73 74 Job *job = malloc(sizeof(union job)); 75 printf("union pointer sizeof(job) = %d\n", sizeof(job) ); 76 77 printf("The Father of the C programming Language Information\n"); 78 printf("-------------------------------------------------------\n"); 79 80 job->name = "Dennis Ritchie"; 81 printf("Name : %s\n" , job->name ); 82 83 job->salary = 1000000000; 84 printf("He‘s salary =%d\n" , job->salary ); 85 86 short sInt = 0; 87 88 printf("short sizeof(short) = %d\n", sizeof sInt ); 89 90 float f = 0.0f; 91 printf("float sizeof(float) = %d\n", sizeof f ); 92 93 double d = 0.0; 94 95 printf("double sizeof(double) = %d\n", sizeof d ); 96 97 98 }
编译命令:cc --std=c89 -W sizeof_complex.c ,未出现任何警告错误输出。编译(0 Warring, 0 Error),编译结果如图所示
执行结果如下:
得到的结论是:
char (字符型) 类型的数据: sizeof 的值是 1;
short (短整型) 类型的数据:sizeof 的值是 2;
int, unsigned (整型,无符号整型)类型的数据: sizeof 的值是 4;
long, unsigned long(长整型,无符号长整型) 类型的数据: sizeof 的值是: 8
float (浮点类型) 类型的数据:sizeof 的值是 4;
double (双精度类型)类型的数据:sizeof 的值是 8;
pointer(指针): 任何指针类型 sizeof 的值是 8
struct(结构体): 结构体 sizeof 值是为 各个成员变量的sizeof之和。
union(联合体): 联合体 sizeof 值是为该联合体的最大长度。
PS:其他编译环境可能会得到不同结果,请注意。
原文:http://www.cnblogs.com/jie1983/p/3536051.html