1.对齐大小,可以设置,若对齐大于结构体中最大类型变量,则按照结构体中最大类型长度进行对齐;
2.类型变量小于对齐大小,则需要进行补齐
#include <stdio.h>
typedef struct{
int a;
double b;
short c;
}Teacher_def;
// 按照8字节进行对齐
/*
a a a a * * * *
b b b b b b b b
c c * * * * * *
sizeof(Teacher_def):24
*/
typedef struct{
double b;
int a;
short c;
}Teacher_def1;
// 按照8字节进行对齐
/*
b b b b b b b b
a a a a c c * *
sizeof(Teacher_def1):16
*/
typedef struct{
char a[3];
int b;
Teacher_def t;
double c;
short d;
}Teacher_def2;
// 按照8字节进行对齐
/*
a a a b b b b *
a a a a * * * *
b b b b b b b b
c c * * * * * *
c c c c c c c c
d d * * * * * *
sizeof(Teacher_def2):48
*/
typedef struct demo{
int a:2;//位空间
int b:3;
int c:4;
double d;
}demo_def;
//按照8字节进行对齐
/*
1bit 1bit 1bit 1bit 1bit 1bit 1bit 1bit 1bit 右补7字节1bit
d d d d d d d d
sizeof(demo_def):16
*/
int main()
{
Teacher_def t;
Teacher_def1 t1;
Teacher_def2 t2;
demo_def demo;
printf("%d\n", sizeof(t));
printf("%d\n", sizeof(t1));
printf("%d\n", sizeof(t2));
printf("%d\n", sizeof(demo));
return 0;
}
运行结果:
24
16
48
16
Press any key to continue
本文深入探讨了C语言中结构体的内存对齐规则及其对结构体大小的影响,通过具体实例展示了不同类型成员在结构体中的布局方式,以及位域在结构体中的应用。
734

被折叠的 条评论
为什么被折叠?



