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

posted @ 2013-01-25 19:16  小尼人00  阅读(338)  评论(0编辑  收藏  举报