当前位置:网站首页>8000 word super detailed custom structure type
8000 word super detailed custom structure type
2022-07-25 21:46:00 【Stay up late and knock code】
Author's brief introduction : Bloggers are studying double non undergraduate courses in accounting , I'm a sophomore now , Is learning JAVA, database , operating system , computer network , data structure ,JAVA Web etc. …
Personal home page : Stay up late and knock code
Work column : C Advanced language
I'm bald , It's getting stronger

List of articles
One 、 Structure
1. Basic knowledge of 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 .
2. Statement of structure
struct tag
{
member-list;
}variable-list;

For example, describe a person :
struct peo
{
char name[20];// name
double len;// height
char sex[6];// Gender
int age;// Age
};// Never lose a semicolon , Fixed format
3. Special structure declaration
When you declare a structure , Incomplete declarations can be made , be called : Anonymous struct type , An anonymous struct type can only be used once .; for example :
struct
{
int x;
int y;
int r;
}a;
So here comes the question , Try to judge in the next interview
struct
{
int a;
char b;
float c
}x;
struct
{
int a;
char b;
float c;
}a[20],*p;
Because it's an incomplete statement , The compiler will treat the above two declarations as completely different types , So it's illegal .The above two structures are declared , It is not completely stated .
Based on the above code , Is the following code legal ?
p=&x;
4. Self reference of structure
Is it possible to include a member whose type is the structure itself ?
struct Node
{
int data;
struct Node next;
};
If you think so , Try to calculate ,sizeof(struct Node) How much is the ? It will cycle wirelessly , Dolls , There is no exact size at all .
The right way to self reference ( Similar to the idea of linked list ):
struct Node
{
int data;
struct Node* next;//4/8 Bytes
};
typedef struct
{
int data;
Node* next;
}Node;
// Whether this is feasible ?

// The right way :
typedef struct Node
{
int data;
struct Node* next;
}Node;
5. Structure variable definition and initialization
There are three ways to define a structure :
struct point
{
int x;
int y;
}p1; // Define variables when declaring types p1
struct point p2; // Define structure type variables p2
struct point p3 = {
1,2 };
// initialization : When defining variables, assign initial values at the same time
Three clock initializes the structure :
struct stu
{
char name[20];
int age;
};
struct stu s = {
"lisi",18 };// initialization
struct Node
{
int data;
struct point p;
struct Node* next;
}n1={
5,{
2,3},NULL};// Global structure variable initialization
struct Node n2 = {
20,{
1,4},NULL };// Structure nesting initialization
6. Structure memory alignment
We have mastered the basic use of structures .
Now let's discuss a problem in depth : Calculate the size of the structure .
This is also a particularly popular test site : Structure memory alignment
// practice 1
struct s1
{
char c1;
int i;
char c2;
};
int main()
{
printf("%d\n", sizeof(struct s1));//12
}

// practice 1
struct S2
{
char c1;
char c2;
int i;
};
int main()
{
printf("%d\n", sizeof(struct S2));//8
return 0;
}

How to calculate ?
First, you have to master the alignment rules of the structure :
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
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 , Nested structures are aligned to an integral multiple of their maximum number of alignments > It's about , The overall size of the structure is the maximum number of alignments ( The number of alignments with nested structures ) Integer multiple
for example :
Introduce a function to calculate the offset to calculate , Are we right .


It completely confirms our guess .
Why is there memory alignment ?
- 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 , 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 .
struct S1
{
char c1;
int i;
char c2
};
struct S2
{
char c1;
char c2;
int i;
};
int main()
{
printf("%d", sizeof(struct S1));
printf("%d", sizeof(struct S2));
return 0;
}
In the same structure , Let the members with small space together , More space saving

7. Change the default alignment number
In some cases , System default 8 Byte alignment is a bit too space wasting , You have to change the default alignment number ,#pragma This preprocessing instruction can complete this function .
#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\n", sizeof(struct S1));
printf("%d\n", sizeof(struct S2));
return 0;
}

When the default alignment number does not meet the requirements , We can customize the default alignment number .
8. Structural parameters
Two different ways of transferring parameters , as follows :
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(struct S* ps)
{
printf("%d\n", ps->num);
}
int main()
{
print1(s); // Transmissive structure
print2(&s); // Address
return 0;
}
Both can be printed normally , But which one is better ?
The preferred print2
reason :
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 can lead to performance degradation .
Two . Bit segment
1. What is a bit segment
The declaration and structure of a bit segment are similar , Difference :
1. The member of the segment must be int、unsigned int or signed int .
2. The member name of the segment is followed by a colon and a number .
struct A
{
int _a:2;
int _b:5;
int _c:10;
int _d:30;
};
int main()
{
printf("%d",sizeof(struct A));
return 0;
}

Why not 16?
2. 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 .
struct S
{
char a:3;
char b:4;
char c:5;
char d:4;
};
struct S s = {
0};
s.a = 10;
s.b = 12;
s.c = 3;
s.d = 4;
How to open up space 

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 .
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 , Whether to discard the remaining bits or to 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 .
4. Application of bit segment
Although there are many disadvantages here , But it is widely used in the datagram of computer network .
3、 ... and . enumeration
1. Definition of enumeration
enum Day// week
{
Mon,
Tues,
Wed,
Thur,
Fri,
Sat,
Sun
};
enum Sex// Gender
{
MALE,
FEMALE,
SECRET
};
enum Color// Color
{
RED,
GREEN,
BLUE
};
The above defines three enumeration types .
{} The contents in are the possible values of enumeration , Also known as enumeration constant
These values are valuable , The default from the 0 Start , You can also assign initial values by yourself
enum color// Color
{
RED=1,
YELLOW=5,
BLUE=7
};
2. Advantages of enumeration
We can use #define Define constants , Why do I have to use enumeration ?
Advantages of enumeration :
- Increase the readability and maintainability of the code
- and #define The defined identifier comparison enumeration has type checking , More rigorous .
- Prevent named pollution ( encapsulation )
- Easy to debug
- Easy to use , You can define more than one constant at a time
3. Use of enumeration
In my dynamic address book blog , With application enumeration , Interested partners can have a look at : Specific use of enumeration
enum Color// Color
{
RED=1,
GREEN=2,
BLUE=4
};
enum Color clr = GREEN;// Only enumeration constants can be assigned to enumeration variables , There will be no type difference .
clr = 5; //ok??
Four . union ( Community )
1. The definition of Union
Federation is also 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 :
// Declaration of union type
union Un
{
char c;
int i;
};
// The definition of joint variables
union Un un;
// Calculate the size of the variables
printf("%d\n", sizeof(un));

2. Characteristics of Union
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 the Union has to be able to keep at least the largest member )
union Un
{
int i;
char c;
};
union Un un;
// Is the result of the following output the same ?
int main()
{
printf("%d\n", &(un.i));
printf("%d\n", &(un.c));
return 0;
}

union un
{
int i;
char c;
};
union un un;
// What is the output result below ?
int main()
{
union un un;
un.i = 0x11223344;
un.c = 0x55;
printf("%x\n", un.i);
return 0;
}


3. Classic interview questions ( Judgment of size end )
Method 1:
// Method 1
int check_sys()
{
int a = 1;
return *(char*)&a;
}
int main()
{
int ret = check_sys();
if (ret) // return 1 For the small end
printf(" The small end \n");
else
printf(" Big end \n");
return 0;
}

Method 2( Consortium ):
// Method 2
int check_union()
{
union
{
int i;
char c;
}u;
u.i = 1;
return u.c;
}
int main()
{
int ret = check_union();
if (ret) // return 1 For the small end
printf(" The small end \n");
else
printf(" Big end \n");
return 0;
}

4. 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 .
such as :
union Un1
{
char c[5];
int i;
};
union Un2
{
short c[7];
int i;
};
// What is the output below ?
printf("%d\n", sizeof(union Un1));
printf("%d\n", sizeof(union Un2));


summary
Today comes a custom structure type Grand Slam , As long as you study hard , You will definitely gain a lot , Summer vacation rolls up .

边栏推荐
- Job interviews are always a second kill? After reading the seckill system notes secretly stored by JD T8, I have given my knees
- Six principles of C program design
- Creation and destruction of function stack frames
- Composition of dog food
- [database] index
- [redis underlying parsing] linked list type
- [introduction to C language] zzulioj 1016-1020
- SSH private key realizes login to remote target server
- The noise reduction effect is increased by more than 6 times! With the microphone inside the headset, this wireless noise reduction headset is unusual!
- Optimization analysis of storage structure and IO performance of openharmony littlefs file system
猜你喜欢

Bitcoin.com:USDD代表了真正去中心化稳定币

Zero basic learning canoe panel (17) -- panel CAPL function

Origen foundation officially launched $ogy stacking, leading a new round of ecological benefits

Sentinel vs Hystrix 限流对比,到底怎么选?

Reading the pointpillar code of openpcdet -- Part 3: Calculation of loss function

【饭谈】如何设计好一款测试平台?

腾讯云数据库的可信可控之路

Babbitt | metauniverse daily must read: the popularity of virtual people has decreased, and some "debut is the peak", and the onlookers have dispersed

函数栈帧的创建和销毁
![PHP zero time task, PHP laravel time task schedule [dry goods]](/img/09/c9a4c83fe23c852aa76a6f5a6cea52.png)
PHP zero time task, PHP laravel time task schedule [dry goods]
随机推荐
Handwriting distributed configuration center (1)
Detailed explanation of JVM memory model and structure (five model diagrams)
Job interviews are always a second kill? After reading the seckill system notes secretly stored by JD T8, I have given my knees
立创EDA——器件的创建01-电阻(二)
ES6 -- Deconstruction assignment
【Flink】FLink RocksDBListState 报错 You cannot add null to a ListState
立创EDA——我为什么要学EDA
919. Complete binary tree inserter: simple BFS application problem
FAW red flag "King fried" is listed, which is safe and comfortable
【Redis底层解析】链表类型
Origen foundation officially launched $ogy stacking, leading a new round of ecological benefits
Apple estimates that iPhone will give up the Chinese market, and the Chinese industrial chain needs to consider living a hard life
Redis usage details
Bitcoin.com:usdd represents a truly decentralized stable currency
【饭谈】那些看似为公司着想,实际却很自私的故事 (一:造轮子)
腾讯云数据库的可信可控之路
In Oracle 19C version, logminer package continuous_ The outdated function of mine leads to CDC failure
Autojs learning - file depth search
Vivo official website app full model UI adaptation scheme
大厂面试官:千万级数据量的表,如何进行快速查询?
