1. 程式人生 > 實用技巧 >結構體打包減少佔用測試

結構體打包減少佔用測試

  1 #include <stdio.h>
  2 #include <stdbool.h>
  3 
  4 struct foo1 {
  5     char *p;
  6     char c;
  7     long x;
  8 };
  9 
 10 struct foo2 {
 11     char c;      /* 1 byte */
 12     char pad[7]; /* 7 bytes */
 13     char *p;     /* 8 bytes */
 14     long x;      /* 8 bytes */
 15 };
 16
17 struct foo3 { 18 char *p; /* 8 bytes */ 19 char c; /* 1 byte */ 20 }; 21 22 struct foo4 { 23 short s; /* 2 bytes */ 24 char c; /* 1 byte */ 25 }; 26 27 struct foo5 { 28 char c; 29 struct foo5_inner { 30 char *p; 31 short x; 32 } inner;
33 }; 34 35 struct foo6 { 36 short s; 37 char c; 38 int flip:1; 39 int nybble:4; 40 int septet:7; 41 }; 42 43 struct foo7 { 44 int bigfield:31; 45 int littlefield:1; 46 }; 47 48 struct foo8 { 49 int bigfield1:31; 50 int littlefield1:1; 51 int
bigfield2:31; 52 int littlefield2:1; 53 }; 54 55 struct foo9 { 56 int bigfield1:31; 57 int bigfield2:31; 58 int littlefield1:1; 59 int littlefield2:1; 60 }; 61 62 struct foo10 { 63 char c; 64 struct foo10 *p; 65 short x; 66 }; 67 68 struct foo11 { 69 struct foo11 *p; 70 short x; 71 char c; 72 }; 73 74 struct foo12 { 75 struct foo12_inner { 76 char *p; 77 short x; 78 } inner; 79 char c; 80 }; 81 82 int main(int argc, char *argv) 83 { 84 printf("sizeof(char *) = %zu\n", sizeof(char *)); 85 printf("sizeof(long) = %zu\n", sizeof(long)); 86 printf("sizeof(int) = %zu\n", sizeof(int)); 87 printf("sizeof(short) = %zu\n", sizeof(short)); 88 printf("sizeof(char) = %zu\n", sizeof(char)); 89 printf("sizeof(float) = %zu\n", sizeof(float)); 90 printf("sizeof(double) = %zu\n", sizeof(double)); 91 printf("sizeof(struct foo1) = %zu\n", sizeof(struct foo1)); 92 printf("sizeof(struct foo2) = %zu\n", sizeof(struct foo2)); 93 printf("sizeof(struct foo3) = %zu\n", sizeof(struct foo3)); 94 printf("sizeof(struct foo4) = %zu\n", sizeof(struct foo4)); 95 printf("sizeof(struct foo5) = %zu\n", sizeof(struct foo5)); 96 printf("sizeof(struct foo6) = %zu\n", sizeof(struct foo6)); 97 printf("sizeof(struct foo7) = %zu\n", sizeof(struct foo7)); 98 printf("sizeof(struct foo8) = %zu\n", sizeof(struct foo8)); 99 printf("sizeof(struct foo9) = %zu\n", sizeof(struct foo9)); 100 printf("sizeof(struct foo10) = %zu\n", sizeof(struct foo10)); 101 printf("sizeof(struct foo11) = %zu\n", sizeof(struct foo11)); 102 printf("sizeof(struct foo12) = %zu\n", sizeof(struct foo12));
     return 0;
103 }