- 在C语言中,结构体会以占用字节最长的变量为基准,做内存对齐。
#include<iostream>
#include<stdlib.h>
using namespace std;
struct A
{
//4+4 = 8
char c;
int i;
};
struct B
{
//4+8+4 = 16
char c;
A a;
char b;
};
struct C
{
//4 + 4*4 + 4 = 24
char c;
int a[4];
int i;
};
struct D
{
//4 + 4 = 8
char c;
char b;
int q;
};
struct E
{
//8+8 = 16,以最大的为准,进行对齐填充
int a;
double b;
};
struct F
{
//1 + 1 = 2
char a;
char b;
};
int main()
{
cout<<"the sizeof struct A: "<<sizeof(A)<<endl;
cout<<"the sizeof struct B: "<<sizeof(B)<<endl;
cout<<"the sizeof struct C: "<<sizeof(C)<<endl;
cout<<"the sizeof struct D: "<<sizeof(D)<<endl;
cout<<"the sizeof struct E: "<<sizeof(E)<<endl;
cout<<"the sizeof struct F: "<<sizeof(F)<<endl;
return 0;
}