test.c
#include <stdio.h> struct stu{ char sex; int length; char name[10]; }; int main() { char name[10]; struct stu mystu; printf("size of char:%d\n", sizeof(char)); printf("size of int: %d\n", sizeof(int)); printf("size of char[10]:%d\n", sizeof(name)); printf("size of stu:%d\n", sizeof(mystu)); return 0; }
运行结果
[zxnms@/home/zxnms]$gcc -o test test.c
[zxnms@/home/zxnms]$./test
size of char:1
size of int: 4
size of char[10]:10
size of stu:20
[zxnms@/home/zxnms]$./test
size of char:1
size of int: 4
size of char[10]:10
size of stu:20
主意: 这里的stu不是应该返回1+4+10 = 15吗?
结果分析:
gcc默认按四个字节对齐
struct stu{ char sex; int length; char name[10]; };
sex 1个字节不足4个字节,补足4个字节
length 4个字节
name 8个字节,剩余两个字节:2 不足4个字节
总: 4 + 4 + 8 + 4 = 20