zoukankan      html  css  js  c++  java
  • sizeof()结构体对齐

    struct Test1
    {
    char    name;
    int     score;
    Student *pNext;
    };
    struct Test2
    {
    char    name[3];
    int     score;
    Student *pNext;
    };
    struct Test3
    {
    char    name[6];
    int     score;
    Student *pNext;
    };
    struct Test4
    {
    char    name[30];
    int     score;
    Student *pNext;
    };
    void main()
    {
        int len = sizeof(Test1);   //len = 12
        int len = sizeof(Test2);   //len = 12
        int len = sizeof(Test3);   //len = 16
        int len = sizeof(Test4);   //len = 40
    }
    //VS2008,编译器会将char    name[n];对齐为sizeof(int)的倍数。也就是4的倍数,如果不够4的倍数会+上最小的数字达到4的倍数。
    因为这个结构体内占字节数最大的基本类型是int.

    再举例,如果是这样
    struct Test1
    {
    char    name[10];
    int     score;
    char    oldName;
    };

    struct Test2
    {
    char    name[10];
    short     score;
    char    oldName;
    };
    void main()
    {
        int len = sizeof(Test1);   //len = 20
        int len = sizeof(Test2);   //len = 14
    }
    test1 把结构体内的属性以sizeof(int)对齐,char name[10]补齐到12,char    oldName补齐
    到4,所以12 + 4 +4 =20。
    test2以sizeof(short)对齐,10 = sizeof(name)已经是2的倍数,不用补齐。所以是12 + 2 + 2
    =14

    顺序的影响

    typedef struct _AAA
    {
    char b;
    double a;
    char c;
    }AAA;

    typedef struct _AAA
    {
    char b;
    char c;
    double a;

    }AAA2;

    void main()
    {
    len = sizeof(AAA);          //len 24
    len = sizeof(AAA2);        //len 16
    }

  • 相关阅读:
    PyQt5--Buttons
    PyQt5--Position
    PyQt5--ShowWindowCenter
    PyQt5--MessageBox
    PyQt5--CloseWindow
    PyQt5--ShowTips
    PyQt5---ChangeIcon
    PyQt5---firstwindow
    PyQt5--StatusBar
    PyQt5 的几个核心模块作用
  • 原文地址:https://www.cnblogs.com/yuzhould/p/4454994.html
Copyright © 2011-2022 走看看