我定义了一个struct:typedef struct
{
 char sign;
 int size;
 char data[1];
} DATA;
其 sizeof(DATA) 的值为12,而typedef struct
{
 int size;
 char sign;
 char data[1];
} DATA;
其 sizeof(DATA) 的值为8,另外,typedef struct
{
 int size;
 char sign;
 char data[3];
} DATA;
其 sizeof(DATA) 的值也是8,这是怎么回事?编程环境为VC++6.0,sizeof(int)=4,sizeof(char)=1我认为上面两个是等价的,结果为6,而下面两个结果应该是不相同的
高手指点啊

解决方案 »

  1.   

    建议察看有关数据对齐方面的资料,这个东西和cpu和编译器有关系
      

  2.   

    When you apply the sizeof operator to a structure or union type name, or to an identifier of structure or union type, the result is the number of bytes in the structure or union, including internal and trailing padding. This size may include internal and trailing padding used to align the members of the structure or union on memory boundaries. Thus, the result may not correspond to the size calculated by adding up the storage requirements of the individual members.字节对齐的概念
      

  3.   

    cpu总是从存储器中取出2^n个字节(n是什么记不清了,应该和cpu位数一致,比如32位cpu的n为2),因此对有的cpu数据地址必须为2^n的倍数,IA32中数据可以是任意地址,但为提高性能仍建议数据对齐.GCC的要求是2字节数据地址为2的倍数,大于2字节的是4的倍数.VC的要求是任何k字节对象的地址都是k的倍数,具体的对齐方式,正如一楼所说,和cpu和编译器有关
      

  4.   

    这是对齐方式的老问题typedef struct
    {
     char sign;//这里要1,从0开始存,0是1的倍数,可以(1)
     int size;//这里要4,由于上面占了0所以从1开始存,1不是4的倍数,所以要+3,使其从最近最
              //小倍数4开始存(1+3+4)
     char data[1];//这里要1,从8开始存,8是1倍数,可以(1+3+4+1)
    } DATA;//上面看到了(1+3+4+1=9,还有个总数要是里面最大byte数的倍数,这里是int即4,所以
           //还要+3,即比9大而又是4的倍数的最小数,那就是12)
    其 sizeof(DATA) 的值为12,而typedef struct
    {
     int size;//4
     char sign;//4+1
     char data[1];//4+1+1
    } DATA;//4+1+1=6不是4的倍数,所以要要+2到8
    其 sizeof(DATA) 的值为8,另外,
      

  5.   

    上面说的是默认的对齐方式,当然你也可以改成以1Byte对齐的方式,如下:#pragma pack(push,1) 式//开始定义数据包, 采用字节对齐方式
    //定义数据包结束,用下面语句恢复默认对齐方式
    #pragma pack(pop)
      

  6.   

    http://dev.csdn.net/develop/article/77/77435.shtm