美文网首页
sizeof(struct)

sizeof(struct)

作者: 远o_O | 来源:发表于2017-08-24 14:39 被阅读4次
    • 在C语言中,结构体会以占用字节最长的变量为基准,做内存对齐。
    #include<iostream>
    #include<stdlib.h>
    using namespace std;
    
    struct A
    {
        //4+4 = 8
        char c;
        int i;  
    };
    
    struct B
    {
        //4+8+4 = 16 
        char c;
        A a;
        char b;
    };
    
    struct C
    {
        //4 + 4*4 + 4 = 24
        char c;
        int a[4];
        int i;  
    };
    
    struct D
    {   
        //4 + 4 = 8
        char c;
        char b;
        int q;  
    };
    
    struct E
    {
        //8+8 = 16,以最大的为准,进行对齐填充 
        int a;
        double b;   
    };
    
    struct F
    {   
        //1 + 1 = 2
        char a;
        char b;
    };
    
    int main()
    {   
        cout<<"the sizeof struct A: "<<sizeof(A)<<endl;
        cout<<"the sizeof struct B: "<<sizeof(B)<<endl;
        cout<<"the sizeof struct C: "<<sizeof(C)<<endl;
        cout<<"the sizeof struct D: "<<sizeof(D)<<endl;
        cout<<"the sizeof struct E: "<<sizeof(E)<<endl;
        cout<<"the sizeof struct F: "<<sizeof(F)<<endl;
        return 0;   
    } 
    
    image.png

    相关文章

      网友评论

          本文标题:sizeof(struct)

          本文链接:https://www.haomeiwen.com/subject/nahedxtx.html