结构体数据对齐问题

 #include < iostream.h >

//-------------------------------------------------------------------
struct     tag_App_0{
 //结构体为空,则其大小为1
}App_0;
//-------------------------------------------------------------------- 
struct     tag_App_1{      
 char a;     //地址0.不需调整    
 char b;     //地址1.不需调整
 long aa;   //地址2,调整为地址4.   +2个为对齐而增的附加空间.  
 long bb;   //地址8,不需调整.                     
}App_1;
//--------------------------------------------------------------------- 
struct     tag_App_2{    
 char a; //地址为0,不需要调整
 long aa;     //地址为1,调整为8
 char b;      //地址为12,不需要调整
 long bb;     //地址为13,调整为16
 
}App_2;
//----------------------------------------------------------------------
struct     tag_App_3{    
 char a; 
 long aa;    
 char b;     
 long bb;   
 
 tag_App_3* p ; 
}App_3;
//----------------------------------------------------------------------
struct     tag_App_4{    
 char a; //地址为0,不需要调整   
 char b;      //地址为1,不需要调整
 tag_App_1 stru1;//地址为4,大小为12
 long aa;     //地址为16,不需要调整
 long bb;     //地址为21,不需要调整  
}App_4;
//---------------------------------------------------------------------- 
int g = sizeof( App_0 ); 
int h = sizeof( App_1 );
int m = sizeof( App_2 ) ;
tag_App_3   temp ;
int n = sizeof( temp.p ) ;
int q = sizeof( App_4 ) ;
//-----------------------------------------------------------------------
void main()

 cout << "App_0 is " << g << endl ;
 cout << "App_1 is " << h << endl ;
 cout << "App_2 is " << m << endl ;
 cout << "App_3 is " << n << endl ;
 cout << "App_4 is " << q << endl ;
 //32位机的int、long int数据类型是32位,short是16位,16位机都是16位long int是32位
 cout << "sizeof( int ) is " <<sizeof( int ) << endl ;
 cout << "sizeof( short int ) is " << sizeof( short int ) << endl ;
 cout << "sizeof( long int ) is " << sizeof( long int ) << endl ;
}
//------------------------------------------------------------------------
//对于定义的结构体,如果其中的成员长度不等,
//这种情况下长度要对齐,不足32位的(32位OS)
//中要补齐32位,所以在定义结构体的时候最好
//把相同类型的成员定义在统一字段,节省资源!

//指向结构体或类对象的指针都是4个字节

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值