当前位置:网站首页>结构体、位段、联合体(共用体)的大小如何计算
结构体、位段、联合体(共用体)的大小如何计算
2022-07-28 05:26:00 【JuLiJuLi.】
结构体的大小如何计算.
如果要计算结构体的大小,我们就必须知道结构体的内存对齐概念,下面来总结下结构体的内存对齐的几点要素:
1. 第一个结构体成员在与结构体变量偏移量为0的地址处。
#include<stdio.h>
struct S1
{
char c1;//1个字节
int i;//4个字节
char c2;//1个字节
};
struct S2
{
char c1;//1个字节
char c2;//1个字节
int i;//4个字节
};
int main()
{
printf("%d\n", sizeof(struct S1));//12
printf("%d\n", sizeof(struct S2));//8
return 0;
}那让我们来看下这个结果是如何得到的呢?

后面我们运行下代码观察下是否与我们分析的一致,

位段的大小该如何计算.
#include<stdio.h>
struct A
{
int _a : 2;
int _b : 5;
int _c : 10;
int _d : 30;
};
int main()
{
printf("%d\n", sizeof(struct A));//8
return 0;
}如果struct A不是位段的话我们知道4个整形的大小是16,那这段代码是如何得到8大小的呢?
先来了解下位段的内存是如何分配的
1. 位段的成员可以是 int unsigned int signed int 或者是 char (属于整形家族)类型的。

我们来运行代码验证下,由于位段涉及很多不确定因素,位段是不跨平台的,注重可移植的程序应该避免使用位段。

联合体(共用体)的大小如何计算.
#include<stdio.h>
union S1
{
char c;
int i;
};
int main()
{
union S1 s;
printf("%d\n", sizeof(s));//4
return 0;
}我们先来看下联合的内存计算规则:
内存计算规则:
1.联合的大小至少是最大成员的大小,(因为联合至少得有空间能保存那个最大的成员)


边栏推荐
- 七夕礼物送女生什么好?颜值在线又有心意的礼物推荐
- 新的selenium
- set_ multicycle_ path
- 使用wampserver3.2.6时切换中文时造成启动失败
- qt设置加载界面的几种方法
- 2022年七夕礼物推荐!好看便宜又实用的礼物推荐
- Vscode中,无法打开源文件 “Adafruit_GFX.h“
- 2022年七夕送女朋友什么礼物好?实用且好看的礼物推荐
- Cronbach’s α? Kmo coefficient? Factor load? The most understandable course of questionnaire reliability and validity analysis in history!!! (SPSS and AMOS)
- MFC 使用控制台打印程序信息
猜你喜欢
随机推荐
Find the network address and broadcast address of the host according to the IP address and subnet mask
clickhouse建宽表多少列最合适?
IP地址的五大分类
七夕送什么礼物最实用?送人绝对不会出错的礼物值得买
自定义组件--纯数据字段&组件的生命周期
小程序自定义组件-数据,方法和属性
Solve the problem that the memory occupation is higher than that of the application process
自定义组件--样式
Icc2 (IV) routing and postroute optimization
OpenGL的开发环境配置【VS2017】+常见问题
详解安装msdn 2015及其注意事项
Common table expression CTE in Clickhouse
气导贴耳式耳机推荐、不需要佩戴入耳的气传导耳机
Introduction to Perl (IX) quotation
Matlab simulation of radar imaging 2 - pulse compression and windowing
Relative path and absolute path
qt自定义滑动按钮(美观且使用方便)
2022-07-19 达梦数据库 连接实例、执行脚本、系统命令
npm yarn相关的操作
QT solves the problem of rebuilding UI files every time they are modified









