大疆笔试题 struct大小实例

本文探讨了在32位环境下,针对大疆笔试中涉及的struct类型的大小问题。通过一个简单的C++代码示例,揭示了内存对齐规则和结构体成员在内存中的布局方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}


内存对齐的三条重要原则

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值