当前位置:网站首页>结构体、位段、联合体(共用体)的大小如何计算
结构体、位段、联合体(共用体)的大小如何计算
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.联合的大小至少是最大成员的大小,(因为联合至少得有空间能保存那个最大的成员)


边栏推荐
- Hugging face 的问题记录 I
- OpenGL快速配置方法
- npm yarn相关的操作
- ubuntu mysql 设置远程访问权限
- error: redefinition of ‘xxx‘
- Common table expression CTE in Clickhouse
- Several methods of QT setting loading interface
- QT painting event - set background picture
- Monitor the CPU temperature of raspberry pie 4B installed with esxi on ARM
- VI and VIM commands
猜你喜欢

Monitor the CPU temperature of raspberry pie 4B installed with esxi on ARM

自定义组件--父子组件之间的通信

Machine learning note 5 - logistic regression

Pycharm2019 set editor theme and default code

多个ics日历合并成单个ics日历

气传导蓝牙耳机怎么样、最值得入手的气传导耳机

Servlet

Explain the installation of MSDN 2015 and precautions

一、ffmpeg录制音频为pcm文件

qt批量操作控件,并设置信号槽
随机推荐
Servlet
How many columns are the most suitable for Clickhouse to build a width table?
[untitled]
ubunut 服务器上传下载文件
Perl introductory learning (VIII) subroutine
In vscade, the source file "adafruit_gfx.h" cannot be opened“
qt中获取当前目录
scrapy 定时执行
【学习笔记】线程创建
2021-11-10
JSP实现文件上传功能的同时还要向后台传递参数
小程序:生命周期
[yolov5] environment construction: win11 + mx450
一、ffmpeg录制音频为pcm文件
Introduction to Perl (IX) quotation
ubuntu mysql 设置远程访问权限
execjs 调用
OpenGL quick configuration method
刷题记录----二叉树
2022-05-24 SpEL使用