当前位置:网站首页>Struct, bit segment, enumeration, union
Struct, bit segment, enumeration, union
2022-07-02 22:32:00 【Hao Shaokang】
This blog mainly focuses on the use of these four custom types and some details .

Structure struct S There are three member variables in the , Respectively char,int,char type , All in all 6 Bytes , And the result shows that the size is 12 Bytes , The reason is that the structure has memory alignment rules .

offsetof Is a macro , You can calculate an offset of the structure member relative to the starting memory of the structure ( Unit is byte ), From this, we can analyze the distribution of each member variable in memory , Here's the picture , In fact, the storage of structure member variables follows the rules of memory alignment .

Structure memory alignment rules :
1. The first member is saved to the structure variable with an offset of 0 The address of
2. Other member variables need to be aligned to a number ( Align numbers ) At an integer multiple offset of , Align numbers = The compiler defaults to an alignment number and the smaller value of the member size (vs The default number of alignments in is 8)
3. The total size of the structure is an integral multiple of the maximum number of alignments ( Each member has an alignment number )
4. If the structure is nested with a structure , The nested structure is aligned to an integral multiple of its maximum alignment , The overall size of the structure is an integral multiple of the maximum alignment number ( The number of alignments with nested structures )
Why is there memory alignment ?
1. Platform reasons ( Reasons for transplantation )
Not all hardware platforms can access data at any address , Some hardware platforms can only access certain specific data at certain addresses , Otherwise, the hardware is abnormal
2. Performance reasons :
To access unaligned memory , The processor may need to make two memory accesses , The aligned memory only needs to be accessed once , Improved efficiency , Memory alignment of structures is the practice of exchanging space for time .
Bit segment :

The bit segment can be seen in the above figure struct S1 It takes up three bytes of memory space , So how is the specific memory allocated to each member , Each member variable is char type , So allocate one byte at a time . First, open up a byte space ,a Occupied 3 individual bit, b Occupied 4 individual bit, And then there were one bit, and c need 5 individual bit, Then open up another byte space , In the end c Is to occupy the remaining one bit, Occupy the second byte 4 individual bit, Or waste the remaining one bit, Occupying the second byte 5 individual bit Well ? Actually c Language itself has no rules , How to occupy depends on the compiler ( Therefore, bit segments do not have cross platform )(vs Middle is the second way ),c Occupying the second byte 5 individual bit, Three left bit, Not enough d Occupy , So open up a third byte , therefore struct S1 Co occupation 3 Bytes .
Since the a and b Are stored in the first byte , that a Is it to occupy the high position or the low position first , This is uncertain , We assume that a Occupy the low position first ,, that b Occupy a high position , The data should be 62 03 04


According to the memory, we can see that the result is the same as we expected , So when bit segment members are stored in the same byte , Occupy the low position first , Occupy a high position after .

struct S2 The member variables in are int type , So we first open up four byte space ,a It took two bit,b It takes five bit,c Occupied 10 individual bit, And then there were 15 individual bit, Not enough d Of 30 individual bit, So open up another four bytes ,d Occupy the post development 32 individual bit Medium 30 individual bit.
The advantage of bit segment is to reduce memory consumption , But there are also some problems with bit segments
The cross platform problem of bit segment :
1.int It's uncertain whether a bit segment is treated as a signed number or an unsigned number
2. The number of the largest bits in the bit segment cannot be determined (16 Bit machine int Occupy 16bit,32 Bit machine int Occupy 32bit)
3. The members in the bit segment are allocated from left to right in memory , Right to left distribution is still uncertain ( Two member variables occupy the high position first in the same byte , Or occupy the low position first )
4. When a structure contains two bit segments , The second member is larger , Cannot hold the remaining bits of the first bit segment , Is to discard the remaining bits , Or use , This is uncertain .
enumeration :

Enumeration types may take values MALE,FEMALE,SECRET The initial values are 0,1,2. However, the initial value can be changed

union ( Shared body ):

The special feature of the consortium is that member variables share the same memory space ,( You can see from the printed address )
The size of the consortium :
1. The size of the consortium is at least the size of the largest member
2. If the size of the largest member is not an integer multiple of the maximum alignment number , Align to an integer multiple of the maximum number of alignments

边栏推荐
- ServiceMesh主要解决的三大痛點
- Infrastructure is code: a change is coming
- Market Research - current situation and future development trend of herringbone gear Market
- Ransack组合条件搜索实现
- 20220702-程序员如何构建知识体系?
- Market Research - current situation and future development trend of marine clutch Market
- Phpcms realizes the direct Alipay payment function of orders
- Official announcement! The golden decade of new programmers and developers was officially released
- Kubernetes resource object introduction and common commands (4)
- sql service 截取字符串
猜你喜欢

Evolution of messaging and streaming systems under the native tide of open source cloud

【ODX Studio编辑PDX】-0.1-如何快速查看各Variant变体间的支持的诊断信息差异(服务,Sub-Function...)

The failure rate is as high as 80%. What should we do about digital transformation?
![[shutter] shutter page life cycle (initialization period | createstate | initstate | update period | build | destroy period | dispose)](/img/07/6f2dfb543cb0ab4f27169da7e6ad07.jpg)
[shutter] shutter page life cycle (initialization period | createstate | initstate | update period | build | destroy period | dispose)

Basic concepts of image and deep understanding of yuv/rgb

Interpretation of CVPR paper | generation of high fidelity fashion models with weak supervision

Phpcms realizes the direct Alipay payment function of orders

Error in PIP installation WHL file: error: is not a supported wheel on this platform

#include errors detected. Please update your includePath.

Scrcpy this software solves the problem of sharing mobile screen with colleagues | community essay solicitation
随机推荐
Service visibility and observability
图像基础概念与YUV/RGB深入理解
Pointer and string
[sword finger offer] 56 - I. the number of numbers in the array
UE4 UI自适应屏幕
A week's life
[001] [arm-cortex-m3/4] internal register
Web侧防御指南
Ransack组合条件搜索实现
Secondary development of ANSYS APDL: post processing uses command flow to analyze the result file
20220702 how do programmers build knowledge systems?
PHP微信抢红包的算法
20220702-程序员如何构建知识体系?
《ActBERT》百度&悉尼科技大学提出ActBERT,学习全局局部视频文本表示,在五个视频-文本任务中有效!
Market Research - current situation and future development trend of carob chocolate market
Unity3d learning notes 4 - create mesh advanced interface
[QT] QT multithreading development - four methods to realize multithreading design
Riding the wind of "cloud native" and stepping on the wave of "digitalization", new programmer 003 starts pre-sale
540. Single element in ordered array
The source code of the daily book analyzes the design idea of Flink and solves the problems in Flink