当前位置:网站首页>Structure memory alignment, bit segment, union
Structure memory alignment, bit segment, union
2022-07-19 12:27:00 【Er Mu】
List of articles
One 、 Structure memory alignment
How to calculate the size of a structure ?
First, you have to master the alignment rules of the structure :
- The first member is associated with the structure variable The offset for the 0 The address of .
- Other member variables should be Align to a number ( Align numbers ) Integer multiple The address of .
Align numbers = The compiler defaults to an alignment number and the smaller value of the member size .
VS The default value in is 8 - The total size of the structure is Maximum number of alignments ( Each member variable has an alignment number ) Integer multiple .
- If the structure is nested , The nested structure is aligned to an integral multiple of its maximum alignment , The integrity of the structure
Body size is all Maximum number of alignments ( The number of alignments with nested structures ) Integer multiple .
Do not understand ? Just do a few questions .
Exercise one :
#include <stdio.h>
struct s1
{
char c1;
int i;
char c2;
}s1;
int main()
{
printf("%d\n", sizeof(s1));
return 0;
}

Exercise 2 :
struct S2
{
char c1;
char c2;
int i;
};
printf("%d\n", sizeof(struct S2));

Practice three :
#include <stdio.h>
struct S3
{
double d;
char c;
int i;
};
int main()
{
printf("%d\n", sizeof(struct S3));
return 0;
}

Exercise four : Nested structure
#include <stdio.h>
struct S3
{
double d;
char c;
int i;
};
struct S4
{
char c1;
struct S3 s3;
double d;
};
int main()
{
printf("%d\n", sizeof(struct S4));
return 0;
}

- Why is there memory alignment ?
Most of the references say that :
Platform reasons ( Reasons for transplantation ):
Not all hardware platforms can access any data on any address ; Some hardware platforms can only access certain types of data at certain addresses , Otherwise, a hardware exception will be thrown .Performance reasons :
data structure ( Especially stacks ) It should be aligned as far as possible on the natural boundary .
The reason lies in , To access unaligned memory , The processor needs to make two memory accesses ; The aligned memory access only needs one access .
On the whole :
Memory alignment of structures is a way of trading space for time
When designing structures , If we want to meet both alignment , And save space , Just do it :
Let the members who occupy less space gather together as much as possible .
- Change the default alignment number :
When the structure is not aligned properly , We can change the default alignment number by ourselves .
#include <stdio.h>
#pragma pack(8)// Set the default alignment number to 8
struct S1
{
char c1;
int i;
char c2;
};
#pragma pack()// Unset the default number of alignments , Restore to default
#pragma pack(1)// Set the default alignment number to 1
struct S2
{
char c1;
int i;
char c2;
};
#pragma pack()// Unset the default number of alignments , Restore to default
int main()
{
// What is the result of the output ?
printf("%d ", sizeof(struct S1));
printf("%d", sizeof(struct S2));
return 0;
}
The output is :12 6
Two 、 Bit segment
- What is a bit segment
The declaration and structure of a bit segment are similar , There are two differences :
- The member of the segment must be
int、unsigned int、signed int or char. - The member name of the segment is followed by a colon and a number .
Such as :
struct A
{
int _a:2;
int _b:5;
int _c:10;
int _d:30;
};
A It's a bit segment type , that A What's the size of ?
To answer this question , We must know the memory allocation of bit segments :
- The members of a segment can be int 、unsigned int、 signed int Or is it char ( It belongs to the integer family ) type
- The space of the bit segment is based on 4 Bytes (int) perhaps 1 Bytes (char) The way to open up .
- Bit segments involve many uncertainties , Bit segments are not cross platform , Pay attention to portable program should avoid using bit segment .
example :
#include <stdio.h>
struct S
{
char a : 3;
char b : 4;
char c : 5;
char d : 4;
};
int main()
{
struct S s = {
0 };
s.a = 10;
s.b = 12;
s.c = 3;
s.d = 4;
printf("%d\n", sizeof(s));
return 0;
}

The cross platform problem of bit segment :
- int It's uncertain whether a bit segment is treated as a signed number or an unsigned number .
- The number of the largest bits in the bit segment cannot be determined .(16 The machine is the largest 16,32 The machine is the largest 32, It's written in 27, stay 16 A bit of the machine will go wrong )
- The members in the bit segment are allocated from left to right in memory , Or right to left allocation criteria have not yet been defined .
- When a structure contains two bit segments , The second segment is relatively large , Cannot hold the remaining bits of the first bit segment , yes
Discard the remaining bits or use , This is uncertain .
- summary :
Compared with the structure , Bit segments can achieve the same effect , But it can save a lot of space , But there are cross platform problems .
3、 ... and 、 union
1. Definition of joint type
Union is a special custom type
Variables defined by this type also contain a series of members , The feature is that these members share the same space ( So union is also called community ).
Such as :
#include <stdio.h>
// Declaration of union type
union Un
{
char c;
int i;
};
// The definition of joint variables
union Un un;
// Calculate the size of the joint variable
int main()
{
printf("%d\n", sizeof(un));// Output 4
return 0;
}
2. Characteristics of the consortium
Members of the union share the same memory space , The size of such a joint variable , At least the size of the largest member ( Because of couplet
At least have the ability to save the largest member ).
#include <stdio.h>
union Un
{
int i;
char c;
};
union Un un;
int main()
{
// Is the result of the following output the same ?
printf("%p\n", &(un.i));
printf("%p\n", &(un.c));
// What is the output below ?
//un.i = 0x11223344;
//un.c = 0x55;
//printf("%x\n", un.i);// Output 11223355
return 0;
}
3. Calculation of joint size
- The size of the union is at least the size of the largest member .
- When the maximum member size is not an integral multiple of the maximum number of alignments , It's about aligning to an integer multiple of the maximum number of alignments .
example :
#include <stdio.h>
union Un1
{
char c[5];
int i;
};
union Un2
{
short c[7];
int i;
};
int main()
{
// What is the output below ?
printf("%d\n", sizeof(union Un1));//8
printf("%d\n", sizeof(union Un2));//16
return 0;
}
summary
That's all for this article , If there is a mistake , Please correct me. .
边栏推荐
- 超声波传感器(CH101&ch201) - Ⅱ
- Arbitrum Nova 发布!打造低成本高速度的游戏社交领域专用链
- RAID 磁盘阵列详解,RAID分类及优缺点
- Overview of the application of air, space and sea Association
- Simple implementation of scrapy keyword crawler (take Xinhuanet and people's network as examples)
- 图执行引擎那些事(二)
- 电路故障的分析简略
- JS chain call sleep function ------ "autumn trick punch in Chapter 2"
- Nature | the carbon sequestration rate of groundwater is similar to that of oligotrophic marine system
- HarmonyoS快速入门:Hello world
猜你喜欢

Example of C language drawing - 20 examples of chromatic diagram

Arbitrum Nova 发布!打造低成本高速度的游戏社交领域专用链

Leetcode 150. Evaluation of inverse Polish expression

The leader of the new generation of cloud database -- AWS

第二天实验

Linux下MySQL的安装与使用

Gradient button function button drawing C language example

第五天笔记

动态内存规划

WebGPU 会成为 WebGL 的杀手吗?
随机推荐
RAID 磁盘阵列详解,RAID分类及优缺点
Familiar with nestjs (beginner)
详细分析一个ROS2 CMakeLists.txt文件
HCIP (7)
第二天实验
How to apply applet container technology to develop hybrid app
数组去重 数组排序 最大值 求和 类数组转化 过滤数组
云犀&腾讯云达成战略合作,加速拓展全球直播市场
A skill; Teach you to easily download Tiktok live video, Tiktok live video download new scheme!
PPPoE拨号上网
阿荷投资的思考
SwiftUI Swift 中的数据持久性,保存数据的不同方法
Application of semi supervised learning in malware traffic detection
The leader of the new generation of cloud database -- AWS
若依excel合并单元格导出ExcelUtils
Acwing785. 快速排序
mysql中对于数据库的基本操作
Simple implementation of scrapy keyword crawler (take Xinhuanet and people's network as examples)
Mysql-1366 - Incorrect string value: ‘\xE5\xBC\xA0\xE4\xB8\x89‘ for column ‘userName‘ at row 1
七月集训(第17天) —— 广度优先搜索