C语言字节对齐问题详解
本文转自: https://www.cnblogs.com/clover-toeic/p/3853132.html 引言 考虑下面的结构体定义: 1 typedef struct{ 2 char c1; 3 short s; 4 char c2; 5 int i; 6 }T_FOO; 假设这个结构体的成员在内存中是紧凑排列的,且c1的起始地址是0,则s的地址就是1,c2的地址是3,i的地址是4。 现在,我们编写一个简单的程序: 1 int main(void){ 2 T_FOO a; 3 printf("c1 -> %d, s -> %d, c2 -> %d, i -> %d\n", 4 (unsigned int)(void*)&a.c1 - (unsigned int)(void*)&a, 5 (unsigned int)(void*)&a.s - (unsigned int)(void*)&a, 6 (unsigned int)(void*)&a.c2 - (unsigned int)(void*)&a, 7 (unsigned int)(void*)&a.i - (unsigned int)(void*)&a); 8 return 0; 9 } 运行后输出: 1 c1 -> 0, s -> 2, c2 -> 4, i -> 8 为什么会这样?这就是字节对齐导致的问题。