zoukankan      html  css  js  c++  java
  • [面试] 结构体占用空间的问题,内存对齐~! 真的懂了,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
    */

  • 相关阅读:
    20170620_javaweb_小结
    win7电脑关机时间长怎么办
    hadoop环境搭建之关于NAT模式静态IP的设置 ---VMware12+CentOs7
    初识bigdata时的一些技能小贴士
    mysql 免安装版 + sqlyog 安装 步骤 --- 发的有点晚
    Python开发之IDE选择
    Python解释器换源
    Anaconda安装与使用
    安装Python环境
    Python和其他编程语言
  • 原文地址:https://www.cnblogs.com/robbychan/p/3787158.html
Copyright © 2011-2022 走看看