现在的位置: 首页 > 综合 > 正文

struct 字节对齐问题(不包含struct嵌套的讨论以及修改机器的对齐方式的时候),更详细的请参考收藏

2013年05月16日 ⁄ 综合 ⁄ 共 1002字 ⁄ 字号 评论关闭

    字节对齐掌握4个原则:

            1 与首地址的偏移量必须是变量长度的整数倍

            2 变量按定义的顺序存放

            3 整个结构体的长度必须是最长成员变量长度的整数倍

            4 如果有struct嵌套,则子struct中的变量必须在整个struct符合以上三个原则,但是子struct自身各个变量之间的存储位置不会变。

e.g.

          struct NSSB{
           long a;
           short b;
           char c;
           short d;
           char ch[3];
          }obj,*p;

 cout<<"sizeof long "<<sizeof(long)<<endl;
 cout<<"sizeof double "<<sizeof(double)<<endl;
 cout<<"sizeof float "<<sizeof(float)<<endl;
 cout<<"sizeof int "<<sizeof(int)<<endl;
 cout<<"sizeof short "<<sizeof(short)<<endl;
 cout<<"sizeof char "<<sizeof(char)<<endl;
 cout<<"sizeof p "<<sizeof(p)<<endl;
 cout<<"sizeof *p "<<sizeof(*p)<<endl;

 p=(struct NSSB *)0x1000000;
// cout<<"next struct is "<<(p + 0x1)<<endl;
 //obj.c = 'C';
 cout<<"a "<<&obj.a<<endl;
 cout<<"b "<<&obj.b<<endl;
 cout<<"c "<<&obj.c<<endl;
 cout<<"d "<<&obj.d<<endl;
 cout<<"ch "<<&obj.ch<<endl; 

 

运行结果:

[root@127 test]# ./test.x
sizeof long 4
sizeof double 8
sizeof float 4
sizeof int 4
sizeof short 2
sizeof char 1
sizeof p 4
sizeof *p 16
a 0xbfcee3c0
b 0xbfcee3c4
c d��ο
d 0xbfcee3c8
ch 0xbfcee3ca

 

 

 

抱歉!评论已关闭.