当前位置:网站首页>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 .
边栏推荐
- NPM and yarn update dependent packages
- pollFirst(),pollLast(),peekFirst(),peekLast()
- 08_ Service fusing hystrix
- CUDA programming-05: flows and events
- Ztree custom title attribute
- 07_ Service registration and discovery summary
- Install Oracle under Linux, connect local pl/sql to Oracle import table under Linux, and create new user and password
- HUAWEI 机试题:字符串变换最小字符串 js
- Svg drawing curve
- 罗克韦尔AB PLC 通过RSLinx Classic与PLC建立通信的具体方法步骤
猜你喜欢

对 int 变量赋值的操作是原子的吗?

500 error reporting

JS call and apply

Flex layout (actual Xiaomi official website)

ES6 new - array part

CUDA programming-05: flows and events

flex布局 (实战小米官网)

MySQL transaction
![[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)

Cross domain and processing cross domain
随机推荐
Explicit animation in arkui
How to study happily on station B?
08_ Service fusing hystrix
如何注册码云账号
Longest string without duplicate characters
Data interaction based on restful pages
MySQL基础知识学习(一)
linux安装和远程连接mysql记录
Full Permutation recursive thought sorting
Function anti chattering throttling
Interface test tool -postman usage details
Thermal renewal and its principle
易语言编程: 让读屏软件可获取标签控件的文本
Understand various IOU loss functions in target detection
二叉树讲解
Restful
pollFirst(),pollLast(),peekFirst(),peekLast()
MySQL basic knowledge learning (I)
Mangodb简单使用
New year's goals! The code is more standardized!