当前位置:网站首页>Hard core structure, violent interpretation
Hard core structure, violent interpretation
2022-07-27 09:16:00 【Blue cat Knight】
Speaking of structures : First of all, we should know what is structure
A structure is a collection of values , These values are called member variables . Each member of a structure can be a variable of a different type .
1. Declaration of a structure
Learning structure , First we need to know How is the structure declared .
Next, let's look at two ways to declare a structure
// Declaration of a structure
struct Stu
{
char name[20];// name
int age;// Age
char sex[5];// Gender
char id[20];// Student number
}; // You can't lose the semicolon s1 s2; yes struct Stu type Global variable of // Special statement
// Anonymous struct type
struct
{
int a;
char b;
float c;
}x; The second kind without special declaration has the following two characteristics
struct
{
int a;
char b;
float c;
}x; // Isn't there a name It can only be used once
struct
{
int a;
char b;
float c;
}a[20], * p;
int main()
{
p = &x;
// Although the members of the two structures are the same however p = &x Report warning
// The compiler will treat the above two declarations as two completely different types .
return 0;
}
When the above code runs, the following warning will be reported
![]()
2. Two misunderstandings of self quotation of structure
// Self reference of structure
// Incorrect usage
struct Node
{
int data;
struct Node next; // This will cause the size of this structure Like recursion without jumping out of conditions next There are infinite in it next
};
// therefore Proper use Put the address of the next node
struct Node
{
int data; // Data fields
struct Node* next; // Pointer to the domain // An address to store the next node
};// wrong
typedef struct //typedef Give a new name to the custom data type Node
{ // cause struct To become a // Anonymous struct type //
int data;
Node* next; //Node* next; Inside next It doesn't exist So there's an error
}Node;
// The following methods can be used
typedef struct Node
{
int data;
struct Node* next;
}Node; // here struct Node n And Node n1 equally 3. Structure variable definition and initialization
struct Point
{
int x;
int y;
}p1; // Define variables while declaring types p1
struct Point p2; // Define structure variables p2
struct Point p3 = { 3, 4 };// Define structure variables p33.1 Structure nesting initialization
struct score
{
int math;
char English;
};
struct Stu
{
char name[20];
int age;
struct score s;
};
int main()
{
struct Stu s1 = { "zhangsan",20,{100,'A'} }; // Math scores 100 branch English scores A
printf("%s %d %d %c", s1.name, s1.age, s1.s.math, s1.s.English); // How to print
return 0;
}4. Structure memory alignment
When we are familiar with the basic use of structures , Then consider the size of the structure at a deeper level
The alignment rules of structures :
1. The first member is offset from the structure variable by 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 ( It can be used #pragma pack(8)// Set the default alignment number to 8)
other place The default alignment number of is the size of the member itself
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 ?
Most references say
1. Platform reasons ( Reasons for transplantation ):
Not all hardware platforms can access any data on any address ; Some hardware platforms can only take some special data 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 , To access unaligned memory , The processor needs to make two memory accesses ; Aligned memory access requires only one access
ask .
On the whole :
Memory alignment of structures is a way of trading space for time .

Above picture 9 -->12 Take advantage of The alignment rules of structures The third article in

Compare the above two figures , It's not hard to find out S1 and S2 The type of members as like as two peas , however S1 and S2 There are some differences in the amount of space taken up .
So when we design the structure , We have to satisfy the alignment , And save space , How to do :
Let the members who occupy less space gather together as much as possible .
int main()
{
printf("%d\n", sizeof(struct S1)); // 12
printf("%d\n", sizeof(struct S2)); // 8
return 0;
}Using the above procedure, we can verify .
5. Structural parameters
struct S
{
int data[1000];
int num;
};
struct S s = {
{1,2,3,4}, 1000};
// Structural parameters
void print1(struct S s)
{
printf("%d\n", s.num);
}
// Structure address transfer parameter
void print2(const struct S* ps)
{
printf("%d\n", ps->num);
}
int main()
{
print1(s); // Transmissive structure
print2(&s); // Address
return 0;
}
print1 and print2 What's the difference between the two functions
When a function passes parameters , The parameter is stack pressing , There will be time and space overhead .
If you pass a structure object , The structure is too large , The system overhead of parameter stack pressing is relatively large , So it will lead to performance
falling .
therefore print2 Than print1 Better namely : When structures transmit parameters , We usually need to pass the address of the structure .
After saying these things , Let's talk about Bit end Of Concept
6. What is a bit segment
The declaration and structure of a bit segment are similar , There are two differences :
1. Member of bit segment
int、unsigned int or signed int or char ( It belongs to the plastic family ) type .
2. The member name of the segment is followed by a colon and a number .
for example
struct A
{
//4 byte - 32bit
int _a:2; // 2 Represents bits
int _b:5; // 5 Represents bits
int _c:10; // 10 Represents bits
//32-17 = 15 Not enough.
int _d:30; // 30 Represents bits
};
Guess
sizeof(struct A) How big is the
printf("%d\n", sizeof(struct A)); // 8 Bytes
7. 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 .
// An example
struct S
{
char a:3; // open up 1 byte 8 individual bit -3 = 5
char b:4; // 5- 4 = 1 // here 1 individual bit Be wasted
char c:5; // Reopen
char d:4; // Reopen
};
int main()
{
struct S s = {0};
s.a = 10;
s.b = 12;
s.c = 3;
s.d = 4;
// How space is opened up ?
}

2.3 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 The machine is the largest 16,32 The machine is the largest 32, It's written in 27, stay 16 It's a plane
There will be problems with the device . (16 position int 2 byte 16 individual bit, 32 position int 4 byte 32 individual bit)
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 .
边栏推荐
- Qt中发送信号时参数为结构体或者自定义的类怎么办?
- HUAWEI 机试题:字符串变换最小字符串 js
- [C language - zero foundation lesson 6] input and output sentence format and compound sentence
- Interface test tool -postman usage details
- Babbitt | yuan universe daily must read: Guangzhou Nansha released the "Yuan universe nine" measures, and the platform can obtain up to 200million yuan of financial support
- ArkUI框架中的两个小技巧
- 微信安装包从0.5M暴涨到260M,为什么我们的程序越来越大?
- Five kinds of 3D attention/transformer finishing (a-scn, point attention, CAA, offset attention, point transformer)
- 如何注册码云账号
- Understand various IOU loss functions in target detection
猜你喜欢

Deep understanding of Kalman filter (2): one dimensional Kalman filter

C# 窗体应用常用基础控件讲解(适合萌新)

MySQL transaction

Linux Installation and remote connection MySQL records
![[leetcode -- the first day of introduction to programming ability] basic data type [statistics of odd numbers within the range / average wage after removing the minimum wage and maximum wage)](/img/23/497c013d105d1906ae8a37dd4e18ad.png)
[leetcode -- the first day of introduction to programming ability] basic data type [statistics of odd numbers within the range / average wage after removing the minimum wage and maximum wage)

ES6 new - object part

Ctfshow ultimate assessment

一些实用、常用、效率越来越高的 Kubernetes 别名

How to deploy yolov6 with tensorrt

CUDA programming-04: CUDA memory model
随机推荐
Nutrecipes developed based on arkui ETS
Intel, squeezed by Samsung and TSMC, finally put down its body to customize chip technology for Chinese chips
ES6 new - deconstruction assignment of array / object
flex:1的原理
Rewrite the tensorrt version deployment code of yolox
Svg drawing curve
Specific methods and steps for Rockwell AB PLC to establish communication with PLC through rslinx classic
Tensorflow loss function
async/await的执行顺序以及宏任务和微任务
CUDA programming-04: CUDA memory model
MySQL transaction
【ACL2020】一种新颖的成分句法树序列化方法
5G没能拉动行业发展,不仅运营商失望了,手机企业也失望了
08_ Service fusing hystrix
Full Permutation recursive thought sorting
二叉树讲解
500报错
[leetcode -- the first day of introduction to programming ability] basic data type [statistics of odd numbers within the range / average wage after removing the minimum wage and maximum wage)
Linux Installation and remote connection MySQL records
[micro service ~sentinel] sentinel dashboard control panel