#include <stdio.h>
struct mystruct1
{ // 1字节对齐 4字节对齐
int a; // 4 4
char b; // 1 2(1+1)
short c; // 2 2
};
int main(void)
{
printf("sizeof(struct mystruct1) = %d.\n", sizeof(struct mystruct1));
return 0;
}
结果:sizeof(struct mystruct1) = 8.
分析:当我们没有指定字节对齐的时候,我们的编译器是默认里面的成员变量的最大字节来对齐的,这里面最大是int4字节,所以它是4字节对齐。char是1字节,short是2字节,char+1字节,然后加上short的2字节,就是4字节。char+1字节+short就等于4字节。所以short不用再占4字节。
#include <stdio.h>
struct mystruct1
{
int a; //4字节
char b; //1字节
unsigned short c; //2字节
char *d; //8字节
void (*e) (void); //8字节
};
int main(void)
{
printf("sizeof(struct mystruct1) = %d.\n", sizeof(struct mystruct1));
return 0;
}
结果:sizeof(struct mystruct1) = 24.我们是在Linux64位环境下,所以指针是占8字节
#include <stdio.h>
typedef struct mystruct111
{ // 1字节对齐 4字节对齐
int a; // 4 4
char b; // 1 2(1+1)
short c; // 2 2
short d; // 2 4(2+2)
} My111;
int main(void)
{
printf("sizeof(struct mystruct111) = %d.\n", sizeof(My111));
return 0;
}
结果: izeof(struct mystruct111) = 12.我们看4字节对齐那里就晓得怎么来的了
#include <stdio.h>
struct mystruct1
{ // 1字节对齐 4字节对齐
int a; // 4 4
char b; // 1 2(1+1)
short c; // 2 2
};
typedef struct myStruct5
{ // 1字节对齐 4字节对齐 8字节对齐
int a; // 4 4 4+4
struct mystruct1 s1; // 7 8 8
double b; // 8 8 8
int c; // 4 4 4+4
}MyS5;
int main(void)
{
printf("sizeof(struct mystruct5) = %d.\n", sizeof(MyS5));
return 0;
}
结果:sizeof(struct mystruct5) = 32.
分析:按4字节对齐应该是24,但是我们编译器是按结构体的成员变量最大的字节来对齐的,最大的就是8字节,所以要按8字节对齐,故是32字节。
#include <stdio.h>
#pragma pack(4) //指定4字节对齐
struct mystruct1
{ // 1字节对齐 4字节对齐
int a; // 4 4
char b; // 1 2(1+1)
short c; // 2 2
};
typedef struct myStruct5
{ // 1字节对齐 4字节对齐
int a; // 4 4
struct mystruct1 s1; // 7 8
double b; // 8 8
int c; // 4 4
}MyS5;
#pragma pack()
int main(void)
{
printf("sizeof(struct mystruct5) = %d.\n", sizeof(MyS5));
return 0;
}
结果:sizeof(struct mystruct5) = 24.因为我们指定了4字节对齐,所以现在大小就是24字节
也可以直接在结构体后面指定对齐字节,如下:
typedef struct mystruct111
{ // 1字节对齐 4字节对齐 2字节对齐
int a; // 4 4 4
char b; // 1 2(1+1) 2
short c; // 2 2 2
short d; // 2 4(2+2) 2
}__attribute__((aligned(1024))) My111;//1024字节对齐。__attribute__((aligned(1024)))和My111中间有空格,要特别注意。
我们也可以取消对齐,那么它默认就是1字节对齐
struct mystruct11
{ // 1字节对齐 4字节对齐
int a; // 4 4
char b; // 1 2(1+1)
short c; // 2 2
}__attribute__((packed));//取消字节对齐
本文探讨了结构体在C/C++中的字节对齐原理,通过实例分析了不同对齐方式(1字节、4字节、8字节)下结构体大小的变化,以及如何通过#pragma pack和__attribute__((aligned))控制对齐,重点讲解了实际编程中的应用场景和编译器优化策略。

9337

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



