探索struct & union 存储方式


/*
* test_struct.c
*
* Created on: 2009-10-3
* Author: lengyuex
*/

#include
#include
int main(void)
{
struct str_1{
char a;
int b;
}good1;
struct str_2{
int a ;
char b ;
}good2;
struct str_3{
int a;
char b ;
int c ;
char d ;

}good3;
struct str_4{
int a;
int b;
char c;
char d;

}good4;
struct str_5{
char a;
char b ;
int c ;
int d ;
}good5;
struct str_6{
char a ;
char b ;
int c ;
int d;
double e;
double f ;
}good6;
union uni_1{
char a;
int b;
}good11;
union uni_2{
int a ;
char b ;
}good22;
union uni_3{
int a;
char b ;
int c ;
char d ;

}good33;
union uni_4{
int a;
int b;
char c;
char d;

}good44;
union uni_5{
char a;
char b ;
int c ;
int d ;
}good55;
union uni_6{
char a ;
char b ;
int c ;
int d;
double e;
double f ;
}good66;
printf ("good1:%d\ngood2:%d\ngood3:%d\ngood4:%d\ngood5:%d\ngood6:%d\ngood11:%d\ngood22:%d\ngood33:%d\ngood44:%d\ngood55:%d\ngood66:%d\n",sizeof(good1),sizeof(good2),sizeof(good3),sizeof(good4),sizeof(good5),sizeof(good6),sizeof(good11),sizeof(good22),sizeof(good33),sizeof(good44),sizeof(good55),sizeof(good66));
printf ("char : %d\n",sizeof (char));
printf ("int : %d\n",sizeof (int));
printf ("short :%d\n",sizeof (short));
printf ("long : %d \n",sizeof (long));
printf ("float :%d \n",sizeof (float));
printf ("double :%d \n",sizeof (double));
printf ("a:0x%x,b:0x%x,c:0x%x,d:0x%x,e:0x%x,f:0x%x\n",(unsigned int)&good6.a,(unsigned int)&good6.b,(unsigned int)&good6.c,(unsigned int)&good6.d,(unsigned int)&good6.e,(unsigned int)&good6.f);
exit (0);
}



打印出结果为:

[lengyuex@Tux algorithm]$ ./a.out
good1:8
good2:8
good3:16
good4:12
good5:12
good6:28
good11:4
good22:4
good33:4
good44:4
good55:4
good66:8
char : 1
int : 4
short :2
long : 4
float :4
double :8
a:0xbff7cc9c,b:0xbff7cc9d,c:0xbff7cca0,d:0xbff7cca4,e:0xbff7cca8,f:0xbff7ccb0




主要在第6个的情况下,感觉有些不对,所以后面用地址来验证一下,发现即使有double的情况下,也是4字节对齐的。
posted @ 2009-10-04 00:06  冷月X  阅读(421)  评论(0编辑  收藏  举报