c结构体对齐 2022-12-15 | 2022-12-15 | c语言 | 300 | 1¶前言c语言的字节对齐,机器的大小段模式的理解。计算机存储的基础知识。123456789101112131415161718192021222324252627282930313233#include <stdio.h>typedef struct tm{ unsigned int a;}TM;typedef struct hp{ char a; unsigned char b; TM *t; unsigned short c; unsigned long d;}HP;int main(int argc, char *argv[]){ HP hp={ .a=0xa1, .b=0xb1, .c=0xc1c2, .d=0x1, }; unsigned char *p=&hp; printf("sizeof(HP) = %lu\n",sizeof(HP) ); for (unsigned long i = 0; i < sizeof(HP); ++i) { printf("%02x ",p[i] ); if((i+1)%8==0) printf("\n"); } unsigned int d=hp.d; printf("%d",d); return 0;}1234567//OUT|| sizeof(HP) = 32|| a1 b1 00 00 00 00 00 00 || 00 00 00 00 00 00 00 00 || c2 c1 00 00 00 00 00 00 || 01 00 00 00 00 00 00 00 || 1¶存储方式123456HP hp={ .a=0xa1, .b=0xb1, .c=0xc1c2, .d=0xd1d2d3d4,//<-0x1};1234567//OUT|| sizeof(HP) = 32|| a1 b1 00 00 00 00 00 00 || 00 00 00 00 00 00 00 00 || c2 c1 00 00 00 00 00 00 || d4 d3 d2 d1 00 00 00 00 || 3520254932¶字节对齐12345678//将 d 改为 d:1typedef struct hp{ char a; unsigned char b; TM *t; unsigned short c; unsigned long d:1; //<--- unsigned long d;}HP;1234567//OUT|| 1 warning generated.|| sizeof(HP) = 24|| a1 b1 00 00 00 00 00 00 || 00 00 00 00 00 00 00 00 || c2 c1 01 00 00 00 00 00 || 1少占用了一个8字节。 本文作者: 一塘 本文链接: https://talengu.github.io/public/2022/12/15/c_struct/ 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!