#include<stdio.h> struct A { int A; }; int main() { struct A a; printf("%d\n",sizeof(a)); return 0; }
运行结果:4
#include<stdio.h> struct A { int a; int b; }; int main() { struct A a; printf("%d\n",sizeof(a)); return 0; }
运行结果:8
#include<stdio.h> struct A { int a; char b; }; int main() { struct A a; printf("%d\n",sizeof(a)); return 0; }
运行结果:8
分析:以结构体中最大的数据类型的字节为标准,随后的基础数据类型都会跟随它对齐
#include<stdio.h> struct A { char a; short b; int c; short d; char e; }; int main() { struct A a; printf("%d\n",sizeof(a)); return 0; }
运行结果:12
a |
| b | |
c | |||
d | e |
| |
13 | 14 | 15 | 16 |
32位计算机(主流):
long 8
int 4
short 2
char 1
#include<stdio.h> struct A { char a; short b; char c; int d; long long e; }; int main() { struct A a; printf("%d\n",sizeof(a)); return 0; }
运行结果:24
a |
| b |
c |
| |
d | ||
e |