• [面试] 结构体占用空间的问题,内存对齐~! 真的懂了,cpu取加快速度,省空间来考虑。


    /* 结构体对齐
            原则1、数据成员对齐规则:结构(struct或联合union)的数据成员,第一个数据成员放在offset为0的地方,以后每个数据成员存储的起始位置要从该成员大小的整数倍开始(比如int在32位机为4字节,则要从4的整数倍地址开始存储)。
            原则2、结构体作为成员:如果一个结构里有某些结构体成员,则结构体成员要从其内部最大元素大小的整数倍地址开始存储。(struct a里存有struct b,b里有char,int,double等元素,那b应该从8的整数倍开始存储。)
            原则3、收尾工作:结构体的总大小,也就是sizeof的结果,必须是其内部最大成员的整数倍,不足的要补齐。
    */
    #include <iostream>
    #include <cstring>
    #include <cstdio>
    using namespace std;
    
    struct node1 {
        char c1;
        char c2;
        short s2;
        short s3;
        short s4;
        double d1;
    };
    struct node2 {
        char c1;
        short s2;
        char c2;
        short s3;
        short s4;
        double d1;
    };
    struct node3 {
        char c1;
        char c2;
        short s2;
        int d1;
    };
    struct node4 {
        char c1;
        short s2;
        char c2;
        int d1;
    };
    struct node5 {
        char c1;
        short s2;
        char c2;
    };
    int main() {
        node1 p1;
        cout << sizeof(p1) << endl;
        node2 p2;
        cout << sizeof(p2) << endl;
        node3 p3;
        cout << sizeof(p3) << endl;
        node4 p4;
        cout << sizeof(p4) << endl;
        node5 p5;
        cout << sizeof(p5) << endl;
        return 0;
    }
    /*
    Output~
    16
    24
    8
    12
    6
    */

  • 相关阅读:
    Python自学之乐-python中break continue exit() pass浅析
    Python自学之乐-Python字典实现简单的三级菜单
    Python自学之乐-浅析Python的深浅拷贝
    百度云服务器允许外网访问
    svg究竟是什么?
    基础知识之SQL
    基础知识之html/css/js
    vue基础知识
    数据库基础知识
    Windows 知识基础
  • 原文地址:https://www.cnblogs.com/robbychan/p/3787158.html
Copyright © 2020-2023  润新知