以下结构
typedef struct
{
short a;//2
int   b;//4
char g;//1
char h;//1
double f;//8
}teststruct;在VC下发现size=24?为何不是16?struct内存分配过程是怎样的?
难道是a=4,b=4,g+h=8,f=8   4+4+8+8=24?

解决方案 »

  1.   

    对齐方式的问题高质量C++编程指南
    http://man.chinaunix.net/develop/c&c++/c/c.htm里面讲的很清楚
      

  2.   

    加上#pragma   pack   (1)就是你要的16了
      

  3.   

    字节对齐,去google一下相关文章就可以了
      

  4.   

    内存对齐,为了提高访问效率,编译器会对STRUCT类的东西进行自动填充垃圾字符(PADDING),用于对齐了数据的开头以加快CPU访问的速度
      

  5.   

    typedef struct
    {
    short a;//2
    int   b;//4
    char g;//1
    char h;//1
    double f;//8
    }teststruct;
    这种情况实际上是以8字节对齐的(以最宽的字段对齐)
    a+b=>8,g+h=>8,f=>8
      

  6.   

    既然是8字节对齐,a+b+g+h不是刚好是8么?
      

  7.   

    typedef struct
    {
    double a;//8
    int   b;//4
    char g;//1
    char h;//1
    short f;//2
    }teststruct;
    在VC里sizeof(teststruct)为什么是16
    typedef struct
    {
    short a;//2
    int   b;//4
    char g;//1
    char h;//1
    double f;//8
    }teststruct;在VC里sizeof(teststruct)为什么是24
      

  8.   

    多试了几下,大概明白了,看来我上面的猜测是对的,a=4,b=4,g+h=8,f=8,SIZE=24
    如果是
    typedef struct
    {
    int   b;//4
    short a;//2
    char g;//1
    char h;//1
    double f;//8
    }teststruct;
    则b=4,a=2,g=1,h=1,f=8,SIZE=16如果是
    typedef struct
    {
    double a;//8
    int   b;//4
    char g;//1
    char h;//1
    short f;//2
    }teststruct;
    那就是a=8,b=4;g=1,h=1,f=2这样加起来是16
    但如果是
    typedef struct
    {
    double a;//8
    short f;//2
    int   b;//4
    char g;//1
    char h;//1

    }teststruct1;//size=16
    则是a=8,f=4,b=4,g+h=8,则SIZE=24