总结:
1、结构体对齐过程中以最大类型对齐,结构体大小是其倍数。
2、__attribute__((packed)) 改变其对齐方式为紧凑方式
1、结构体对齐过程中以最大类型对齐,结构体大小是其倍数。
2、__attribute__((packed)) 改变其对齐方式为紧凑方式
3、如果有__attribute__((packed)) struct嵌套使用,则每个结构都要使用__attribute__((packed)),遇到一个问题:在没有都使用__attribute__的时候,保存文件之后,下次读取出来的数据丢失了。
#include<stdio.h>
#include<string.h>
#define _PACKED __attribute__((packed))
struct a
{
char a;
int b;
char c;
char d[10];
};
struct b
{
int b;
char a;
char c;
char d[10];
};
struct c
{
char a;
char c;
int b;
char d[10];
};
struct d
{
char a;
char c;
int b;
char d[10];
}_PACKED;
struct e
{
char a;
char c;
int b;
char d[10];
struct c eec;
char e;
}_PACKED;
int main()
{
int i;
struct a a;
struct b b;
struct c c;
struct d d;
struct e e;
c.a = 'a';
c.b = 20;
c.c = 'c';
c.d[0] = 'd';
c.d[1] = c.d[0]+1;
c.d[2] = c.d[0]+2;
c.d[3] = c.d[0]+3;
c.d[4] = c.d[0]+4;
c.d[5] = c.d[0]+5;
c.d[6] = c.d[0]+6;
c.d[7] = c.d[0]+7;
c.d[8] = c.d[0]+8;
c.d[9] = c.d[0]+9;
e.a = 'A';
e.c = 'C';
e.b = 20;
memcpy(e.d,c.d,sizeof(e.d));
memcpy(&e.eec,&c,sizeof(struct c));
e.e= 'E';
printf("a: a=%p b=%p c=%p\n",&(a.a),&(a.b),&(a.c));
for(i=0;i<10;i++)
{
printf("%p ",&(a.d[i]));
}
printf("\n");
printf("b: a=%p b=%p c=%p\n",&(b.a),&(b.b),&(b.c));
for(i=0;i<10;i++)
{
printf("%p ",&(b.d[i]));
}
printf("\n");
printf("c: a=%p b=%p c=%p\n",&(c.a),&(c.b),&(c.c));
for(i=0;i<10;i++)
{
printf("%p ",&(c.d[i]));
}
printf("\n");
printf("d: a=%p b=%p c=%p\n",&(d.a),&(d.b),&(d.c));
for(i=0;i<10;i++)
{
printf("%p ",&(d.d[i]));
}
printf("\n");
printf("e: a=%c b=%d c=%c\n",e.a,e.b,e.c);
for(i=0;i<10;i++)
{
printf("%c ",e.d[i]);
}
printf("\n");
printf("\nSIZE:%d %d %d %d %d\n",sizeof(struct a),sizeof(struct b),sizeof(struct c),sizeof(struct d),sizeof(struct e));
void *p;
p=&e;
FILE* fp = fopen("e.txt","wr");
fwrite(p,sizeof(struct e),1,fp);
fclose(fp);
fp = fopen("c.txt","wr");
p=&c;
fwrite(p,sizeof(struct c),1,fp);
fclose(fp);
return 0;
}