32位机运行

#include <iostream>

using namespace std;
struct B {
    double a;          
    short c; 
    char b;     
    short d;
};
struct C {
    double a;           
    int b;  
    short c;
    short d;//对其系数2
};
struct D {
    int a;           //对其系数4
    struct C b;   //对其系数8(以c的最大对其参数对其)
    short c;
    short d;//对其系数2
};
struct s1{
    char ch;
    int a;
    double b;
    char c1;
};

struct s2{
    char ch;
    int a;
    double b;
};

int main()
{
cout << "===================B的大小==================" << endl;
cout << "B的大小: " << sizeof(struct B) << endl;
    cout << "a的地址偏移是   " << offsetof(B, a) << endl;
    cout << "c的地址偏移是   " << offsetof(B, c) << endl;
    cout << "b 的地址偏移是   " << offsetof(B, b) << endl;
    cout << "d的地址偏移是   " << offsetof(B, d) << endl<< endl;
    cout << "===================C的大小:==================" << endl;
cout << "C的大小: " << sizeof(struct C) << endl;
    cout << "a的地址偏移是   " << offsetof(C, a) << endl;
    cout << "b 的地址偏移是   " << offsetof(C, b) << endl;
    cout << "c 的地址偏移是   " << offsetof(C, c) << endl;
    cout << "d的地址偏移是   " << offsetof(C, d) << endl<< endl;
    cout << "==================D的大小:===================" << endl;
cout << "D的大小: " << sizeof(struct D) << endl;
    cout << "a的地址偏移是   " << offsetof(D, a) << endl;
    cout << "b 的地址偏移是   " << offsetof(D, b) << endl;
    cout << "c 的地址偏移是   " << offsetof(D, c) << endl;
    cout << "d的地址偏移是   " << offsetof(D, d) << endl<< endl;
    cout << "===================s1的大小:==================" << endl;
    cout << "s1的大小: " << sizeof(struct s1) << endl;
    cout << "ch的地址偏移是   " << offsetof(s1, ch) << endl;
    cout << "a 的地址偏移是   " << offsetof(s1, a) << endl;
    cout << "b 的地址偏移是   " << offsetof(s1, b) << endl;
    cout << "c1的地址偏移是   " << offsetof(s1, c1) << endl<< endl;
    cout << "===================s2的大小==================" << endl;
    cout << "s2的大小: " << sizeof(struct s2) << endl;
    cout << "ch的地址偏移是   " << offsetof(s2, ch) << endl;
    cout << "a 的地址偏移是   " << offsetof(s2, a) << endl;
    cout << "b 的地址偏移是   " << offsetof(s2, b) << endl<< endl;
    return 0;
}
大疆笔试题 struct大小实例

内存对齐的三条重要原则

1:数据成员对齐规则:结构(struct)(或联合(union))的数据成员,第一个数据成员放在offset为0的地方,以后每个数据成员存储的起始位置要从该成员大小的整数倍开始(比如int在32位机为4字节,则要从4的整数倍地址开始存储。 
2:结构体作为成员:如果一个结构里有某些结构体成员,则结构体成员要从其内部最大元素大小的整数倍地址开始存储.(struct a里存有struct b,b里有char,int 
,double等元素,那b应该从8的整数倍开始存储.) 
3:收尾工作:结构体的总大小,也就是sizeof的结果,.必须是其内部最大成员的整数倍.不足的要补齐. 

相关文章:

  • 2021-11-07
  • 2021-04-21
  • 2021-10-08
  • 2022-01-28
  • 2021-10-19
  • 2021-11-17
猜你喜欢
  • 2021-09-09
  • 2022-01-17
  • 2022-12-23
  • 2021-11-09
  • 2021-07-27
  • 2021-10-03
  • 2021-10-03
相关资源
相似解决方案