当前位置:网站首页>Structure of C language (Advanced)
Structure of C language (Advanced)
2022-04-23 11:03:00 【Xiao Wang who learns C language well】
Catalog
1. Memory alignment of structures
Master the alignment rules of structure :
Why is there memory alignment ?
offsetof
Bit segment memory allocation
The cross platform problem of bit segment :
Calculation of the size of the consortium
Friends Hello, everyone. I'm your classmate Xiao Wang
Today I'll bring you the advanced chapter of structure If you think Xiao Wang's writing is good Three in a row ( For collection Please pay attention to Please thumb up ) Thank you for being so nice and paying attention to me ( dog's head )
Xiao Wang's home page : (5 Bar message ) Learn from good examples c Language of Xiao Wang's blog _CSDN Blog - Blogger in the field of brush questions
Xiao Wang's gitee:Gitee Enterprise Edition - Enterprise class DevOps R & D efficiency management platform
If you don't understand the structure, you can see a preliminary article issued by Xiao Wang Structure :(5 Bar message ) C Language —— Structure ( First edition )_ Learn from good examples c Language of Xiao Wang's blog -CSDN Blog

1. Memory alignment of structures 
I believe you have some preliminary understanding of the concept of structure
Now let's discuss a very hot topic How to calculate Size of structure ( excited .jpg)

struct S1 {
char c1; //1 Bytes
int i; //4 Bytes
char c2; // 1 Bytes
};
struct S2 {
char c1; //1 Bytes
char c2; //1 Bytes
int i; //4 Bytes
};
int main() {
struct S1 s1;
struct S2 s2;
printf("%d\n", sizeof(s1));
printf("%d\n", sizeof(s2));
return 0;
}
Read the code above Xiao Wang I already have the answer s1 Its size is 6 s2 It's also 6
however The answer is really 6 Do you
No : The answer is :
![]()
Why 12 and 8 Well How much was wasted byte Well ?
How to calculate ?
Master the alignment rules of structure :
1. The first member is associated with the structure variable The offset for the 0 The address of .
2. Other member variables are aligned to a number ( Align numbers ) An integral multiple of the address of . Align numbers = Compiler default alignment number And The smaller value of the member size .
VS The default value in is 8
3. The total size of the structure is the maximum number of alignments ( Each member variable has an alignment number ) Integer multiple .
4. 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 the maximum number of alignments ( The number of alignments with nested structures ) Integer multiple .
Why is there memory alignment ?
1. Platform reasons ( Reasons for transplantation ): Not all hardware platforms can access any data on any address ; Some hard
The piece platform can only get some special information at some addresses Certain types of data , Otherwise, a hardware exception will be thrown
2. Performance reasons : data structure ( Especially stacks ) It should be aligned as far as possible on the natural boundary . The reason lies in , In order to access Aligned memory , The processor needs to make two memory accesses ; And aligned memory access Only once
in general :
The memory alignment of structures is to trade space for time !



offsetof

offsetof It's calculation Structural members The offset from the starting position
#include<stddef.h>
struct S1 {
char c1; //1 Bytes
int i; //4 Bytes
char c2; // 1 Bytes
};
struct S2 {
char c1; //1 Bytes
char c2; //1 Bytes
int i; //4 Bytes
};
int main() {
struct S1 s1;
struct S2 s2;
printf("%d\n", offsetof(struct S1,c1));
printf("%d\n", offsetof(struct S1, i));
printf("%d\n", offsetof(struct S1, c2));
printf("\n");
printf("%d\n", offsetof(struct S2, c1));
printf("%d\n", offsetof(struct S2, c2));
printf("%d\n", offsetof(struct S2, i));
return 0;
}

Follow the two pictures above s1 s2 The offset starts as like as two peas.

This problem refers to the memory alignment rules of structures written earlier
3. The total size of the structure is the maximum number of alignments ( Each member variable has an alignment number ) Integer multiple .
4. 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 the maximum number of alignments ( The number of alignments with nested structures ) Integer multiple .


Xiao Wang wondered if there was a way to modify the default alignment number ?
The answer is Yes :#pragma This preprocessing instruction , Can change our The default number of alignments .
#pragma pack(1)
struct S1 {
char c1; //1 Bytes
int i; //4 Bytes
char c2; // 1 Bytes
};
struct S2 {
char c1; //1 Bytes
char c2; //1 Bytes
int i; //4 Bytes
int main() {
struct S1 s1;
struct S2 s2;
printf("%d\n", sizeof(s1)); 6
printf("%d\n", sizeof(s2)); 6


We will #pragma pack Changed to 1 became Structure does not exist Memory alignment 了 It won't waste space

Bit segment
What is a bit segment ?
The declaration of bit segments and structs are similar , There are two differences :
1. The member of the bit segment must be int , unsigned、signed int
2. The member name of the bit field is followed by A colon and A number .
such as :
struct A {
int _a;
int _b;
int _c;
int _d;
};
struct AA {
int _a : 2;
int _b : 5;
int _c : 10;
int _d : 30;
};
Bit segment can save space for us under our demand !!
Bit segment memory allocation 
1. The members of a segment can be int unsigned int signed int Or is it char ( It belongs to the plastic family ) type
2. The space of the bit segment is based on 4 Bytes ( int ) perhaps 1 Bytes ( char ) The way to open up .
3. Bit segments involve many uncertainties , Bit segments are not cross platform , Pay attention to portable program should avoid using bit segment .
for instance


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 Maximum 16,32 Bit machine Maximum 32, It's written in 27, stay 16 It's a plane There will be problems with the device .
3. 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 .
4. 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 to the structure , Bit segments can achieve the same effect , But it can save a lot of space , But there are cross platform problems .
Compared to the structure , Bit segments can achieve the same effect , But it can save a lot of space , But there are cross platform problems .

enumeration 
enumeration —— One by one
List the possible values one by one
A week's Monday to Sunday is limited to seven days , You can list them one by one
Gender Yes male Yes Woman You can also list them one by one
In a year 12 Months can also be listed one by one
enum Day// week
{
Mon,
Tues,
Wed,
Thur,
Fri,
Sat,
Sun
};
enum Sex// Gender
{
MALE,
FEMALE,
SECRET
};
enum Color// Color
{
RED,
GREEN,
BLUE
};
As defined above enum Day ,enum color ,enum Sex All enumeration types
{} The contents in are possible values of enumeration types , Also called Enumeration constants . All these possible values have values , The default from the 0 Start , One increment 1, Of course, initial values can also be assigned when defining . for example :

All these possible values have values , The default from the 0 Start , One increment 1, Of course, initial values can also be assigned when defining . for example :


Advantages of enumeration 
1. Increase the readability and maintainability of the code
2. and #define The defined identifier comparison enumeration has type checking , More rigorous .
3. Prevent named pollution ( encapsulation )
4. Easy to debug
5. Easy to use , One time Define multiple constants
Consortium ( Common body )
Definition of joint type 
Federation is also a special custom type
Variables defined by this type also contain a series of members , The characteristic is that these members Share the same space ( So it's also called a consortium )
The rule of a consortium is that only one member can be used at a time
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 ).
Calculation of the size of the consortium
- 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 .
The above is the advanced knowledge of structure brought by Xiao Wang If you think it's well written
Let's offer you our third company
![]()
版权声明
本文为[Xiao Wang who learns C language well]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231053510576.html
边栏推荐
- VIM usage
- Constraintlayout layout
- Diary of dishes | Blue Bridge Cup - hexadecimal to octal (hand torn version) with hexadecimal conversion notes
- Visual common drawing (IV) histogram
- 学习 Go 语言 0x03:理解变量之间的依赖以及初始化顺序
- Mba-day5 Mathematics - application problems - engineering problems
- web三大组件(Servlet,Filter,Listener)
- Visual common drawing (V) scatter diagram
- Learning Notes 6 - Summary of several deep learning convolutional neural networks
- Database management software sqlpro for SQLite for Mac 2022.30
猜你喜欢

Go interface usage

比深度学习更值得信赖的模型ART

Mysql8. 0 installation guide

数据库管理软件SQLPro for SQLite for Mac 2022.30

Excel·VBA自定义函数获取单元格多数值

高价买来的课程,公开了!phper资料分享

第六站神京门户-------手机号码的转换

学习 Go 语言 0x04:《Go 语言之旅》中切片的练习题代码

Reading integrity monitoring techniques for vision navigation systems - 5 Results

Introduction to data analysis 𞓜 kaggle Titanic mission (IV) - > data cleaning and feature processing
随机推荐
Analysis on the characteristics of the official game economic model launched by platoffarm
CUMCM 2021-B:乙醇偶合制備C4烯烴(2)
Mba-day5 Mathematics - application problems - engineering problems
Visual Road (XII) detailed explanation of collection class
FileProvider 路径配置策略的理解
Is the pointer symbol of C language close to variable type or variable name?
Alarm scene recognition
ID number verification system based on visual structure - Raspberry implementation
语雀文档编辑器将开源:始于但不止于Markdown
Ueditor -- limitation of 4m size of image upload component
The difference between restful and soap
More reliable model art than deep learning
Pycharm
最强日期正则表达式
Excel·VBA数组冒泡排序函数
软件测试人员,如何优秀的提Bug?
Intuitive understanding entropy
全栈交叉编译X86完成过程经验分享
Mysql8.0安装指南
Mba-day6 logic - hypothetical reasoning exercises
