首页 > 代码库 > 代码的规划与规范化
代码的规划与规范化
早上在写代码时,为了测试不同数据类型的大小和指针的大小:
1 #include <stdio.h> 2 3 typedef struct info{ 4 char a; 5 char b; 6 char g; 7 char e; 8 int d; 9 int f; 10 int c; 11 }Info; 12 13 int main(int argc, char **argv) 14 { 15 int iVar = 20; 16 long lVar = 26565; 17 char ch = ‘a‘; 18 double dVar = 3.1415926535897932; 19 Info sInfo; 20 21 int *ptriVar = &iVar; 22 long *ptrlVar = &lVar; 23 char *ptrch = &ch; 24 double *ptrdVar = &dVar; 25 Info *ptrsInfo = &sInfo; 26 27 printf("The size iVar %d, lVar %d, ch %d, dVar %d, sInfo %d\n", sizeof(iVar), sizeof(lVar), sizeof(ch), sizeof(dVar), sizeof(sInfo)); 28 printf("The size ptriVar %d, ptrlVar %d, ptrch %d, ptrdVar %d, ptrsInfo %d\n", sizeof(ptriVar), sizeof(ptrlVar), sizeof(ptrch), sizeof(ptrdVar), sizeof(ptrsInfo)); 29 printf("The address ptriVar %p, ptrlVar %p, ptrch %p, ptrdVar %p, ptrsInfo %p\n", &ptriVar, &ptrlVar, &ptrch, &ptrdVar, &ptrsInfo); 30 printf("The value ptriVar %p, ptrlVar %p, ptrch %p, ptrdVar %p, ptrsInfo %p\n", ptriVar, ptrlVar, ptrch, ptrdVar, ptrsInfo); 31 32 return 0; 33 }
结果如下:
The size iVar 4, lVar 8, ch 1, dVar 8, sInfo 16
The size ptriVar 8, ptrlVar 8, ptrch 8, ptrdVar 8, ptrsInfo 8
The address ptriVar 0x7ffdca27f2f8, ptrlVar 0x7ffdca27f2f0, ptrch 0x7ffdca27f2e8, ptrdVar 0x7ffdca27f2e0, ptrsInfo 0x7ffdca27f2d8
The value ptriVar 0x7ffdca27f32c, ptrlVar 0x7ffdca27f320, ptrch 0x7ffdca27f31f, ptrdVar 0x7ffdca27f310, ptrsInfo 0x7ffdca27f300
若代码修改如下:
1 #include <stdio.h> 2 3 typedef struct info{ 4 char a; 5 int c; 6 char b; 7 int d; 8 char e; 9 int f; 10 char g; 11 }Info; 12 13 int main(int argc, char **argv) 14 { 15 int iVar = 20; 16 long lVar = 26565; 17 char ch = ‘a‘; 18 double dVar = 3.1415926535897932; 19 Info sInfo; 20 21 int *ptriVar = &iVar; 22 long *ptrlVar = &lVar; 23 char *ptrch = &ch; 24 double *ptrdVar = &dVar; 25 Info *ptrsInfo = &sInfo; 26 27 printf("The size iVar %d, lVar %d, ch %d, dVar %d, sInfo %d\n", sizeof(iVar), sizeof(lVar), sizeof(ch), sizeof(dVar), sizeof(sInfo)); 28 printf("The size ptriVar %d, ptrlVar %d, ptrch %d, ptrdVar %d, ptrsInfo %d\n", sizeof(ptriVar), sizeof(ptrlVar), sizeof(ptrch), sizeof(ptrdVar), sizeof(ptrsInfo)); 29 printf("The address ptriVar %p, ptrlVar %p, ptrch %p, ptrdVar %p, ptrsInfo %p\n", &ptriVar, &ptrlVar, &ptrch, &ptrdVar, &ptrsInfo); 30 printf("The value ptriVar %p, ptrlVar %p, ptrch %p, ptrdVar %p, ptrsInfo %p\n", ptriVar, ptrlVar, ptrch, ptrdVar, ptrsInfo); 31 32 return 0; 33 }
代码只是调整了下顺序,看结果:
The size iVar 4, lVar 8, ch 1, dVar 8, sInfo 28
The size ptriVar 8, ptrlVar 8, ptrch 8, ptrdVar 8, ptrsInfo 8
The address ptriVar 0x7ffe514d7ba8, ptrlVar 0x7ffe514d7ba0, ptrch 0x7ffe514d7b98, ptrdVar 0x7ffe514d7b90, ptrsInfo 0x7ffe514d7b88
The value ptriVar 0x7ffe514d7bec, ptrlVar 0x7ffe514d7be0, ptrch 0x7ffe514d7bdf, ptrdVar 0x7ffe514d7bd0, ptrsInfo 0x7ffe514d7bb0
可以看到,仅仅是在定义结构体时的顺序不同,结构体的大小就有这么大差距,原因是C语言中会自动对结构体予以空间填充,因此要合理利用这一点。代码的规范和规划是必要的。
代码的规划与规范化