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


边栏推荐
猜你喜欢

Matlab simulation of radar imaging 4 - range resolution analysis

Antenna effect solution

2022年七夕礼物推荐!好看便宜又实用的礼物推荐

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

Matlab simulation of radar imaging 3 - multi-target detection

clickhouse建宽表多少列最合适?

小程序:wsx脚本

Machine learning note 5 - logistic regression

Explain the installation of MSDN 2015 and precautions

vi和vim命令
随机推荐
USB network native driver for esxi updated to support esxi7.0 Update 2
气导贴耳式耳机推荐、不需要佩戴入耳的气传导耳机
mysql join技巧
NPM yarn related operations
Five categories of IP addresses
气传导蓝牙耳机哪个好、气传导蓝牙耳机排行榜
MySQL join skills
万字归纳总结并实现各大常用排序及性能对比
Machine learning note 5 - logistic regression
MySQL delete tables without deleting databases
转义字符笔记
C语言的文件操作
2022-05-15 基于jwt令牌token
刷题记录----二叉树的层序遍历
Pytorch learning note 4 - automatic calculation of gradient descent autograd
Esxi on ARM v1.2 (updated in November 2020)
自定义组件--父子组件之间的通信
Introduction to Perl (IX) quotation
Filter
Pytorch learning notes 1 - quick start