首页 > 解决方案 > 结构成员对齐和填充明确的活动

问题描述

在此处输入图像描述

尝试以下代码- https://onlinegdb.com/H1Sf_PAiI

#include<iostream>
using namespace std;

struct Str
{
    char c;
    int ch1:56;
    double d;
    int s;
    int ch:32;  
}st;
int main()
{
    cout<<sizeof st<<endl;

    return 0;
}

输出

main.cpp:7:10: warning: width of ‘Str::ch1’ exceeds its type                                                                          
32

然后我将 ch1 位字段减少到 32 位。有效..!

尝试以下代码- https://onlinegdb.com/BkD4YP0oI

#include<iostream>
using namespace std;

struct Str
{
    char c;
    int ch1:32;
    double d;
    int s;
    int ch:32;  
}st;
int main()
{
    cout<<sizeof st<<endl;

    return 0;
}

输出

24

上图中的规则 1 和 2 不正确?

标签: c++paddingmemory-alignment

解决方案


推荐阅读