当前位置:网站首页>Struct, enum type and union
Struct, enum type and union
2022-07-25 20:34:00 【Smart Knight】
Catalog
One 、 The basic use of structures
2. General declaration of structure
3. Special declaration of structure
4. Self reference of structure
5. Structure variable definition and initialization
Two 、 Structure memory alignment
3. Why is there memory alignment
4. Change the default alignment number
2. Bit segment memory allocation
3. The cross platform problem of bit segment
5、 ... and 、 union ( Shared body )
2. Calculation of the size of the consortium
One 、 The basic use of structures
1. What is a structure
The structure is C Important knowledge points in language , The structure makes C Language has the ability to describe complex types .
For example, describe a student , A student includes : name + Age + Gender + Student number .
We can't describe such a complex object with basic data types , Here we can only use structure to describe .
2. General declaration of structure
struct Stu//struct Represents the creation of a structure ,Stu Represents the structure label , The type of data is struct Stu
{
char name[20];// name
int age; // Age
char sex[10]; // Gender
char id[15]; // Student number
}s;// This s Is a structural variable
// When this structure is defined in main When inside a function ,s It's a local variable ; stay mian Out of function , Is a global variable 3. Special declaration of structure
We can also omit the label of the structure
struct
{
int a;
char b;
float c;
}x;
struct
{
int a;
char b;
float c;
}a[20], *p;//a[20] Is an array of twenty structures ,p Is a pointer variable to such a structure
p = &x;// Although the structure above has no label , But these are still two different structures , So we can't recognize each other 4. Self reference of structure
First, we introduce the concept of linked list , Like clues in a treasure hunt , You have a clue , Then follow this clue to find , You'll find the next clue , Follow the clues you find , You will find the next clue , In this way, you can finally find the treasure , All the clues are connected .
If you store the information of the next layer in the data of the previous layer , Then this layer of information can be constantly looked down , Our data is also linked , This is a simple generalization of a linked list .
Similar to the idea of linked list , The structure can reference itself .
struct Node
{
int data;
struct Node next;
};
// But this is not allowed , This program will constantly look internally struct node nest,sizeof Can't calculate
// modify
struct Node
{
int data;
struct Node* next;
};
// The pointer is correct , The size of the pointer variable is fixed typedef struct
{
int data;
Node* next;
}Node;
// error , Because the type redefinition is used without reading all
typedef struct Node
{
int data;
struct Node* next;
}Node;
// correct 5. 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 = {x, y};
// initialization : Define variables and assign initial values at the same time .
struct Stu
{
char name[15];// Gender
int age;// Age
};
struct Stu s = {"zhangsan", 20};// initialization
struct Node
{
int data;
struct Point p;
struct Node* next;
}n1 = {10, {4,5}, NULL};
// Structure nesting initialization
struct Node n2 = {20, {5, 6}, NULL};
// Structure nesting initialization Two 、 Structure memory alignment
1. Memory alignment rules
For any type of data, we have a relationship with its size , Structure is no exception .
- But different from different data types , The structure has its own memory usage mode , That's memory alignment .
- The first member is offset from the structure variable by 0 The address of .
- 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
- The total size of the structure is the maximum number of alignments ( Each member variable has an alignment number ) Integer multiple .
- If the structure is nested , The nested structure is aligned to an integral multiple of its maximum alignment , The overall size of the structure is the maximum number of alignments ( The number of alignments with nested structures ) Integer multiple .
2. Give an example of
#include<stdio.h>
struct A
{
int a;// 4/8->4 0 1 2 3
short b;// 2/8->2 4 5
int c;// 4/8->4 8 9 10 11
char d;// 1/8->1 12
};
struct B
{
int a;// 4/8->4 0 1 2 3
short b;// 2/8->2 4 5
char c;// 1/8->1 6
int d;// 4/8->4 8 9 10 11
};
int main()
{
printf("%d %d", sizeof(struct A), sizeof(struct B));
return 0;
}The result of this program is :16 12, This proves that The storage of structures is not a simple stack of data .
Next , We analyze :
First of all, let's analyze struct A:
(1) The first element is stored at an offset of 0 The address of ,int Variables of type account for 4 byte , It will occupy an offset of 0、1、2、3 These four bytes .
(2) The storage of the second element needs to consider the default alignment number ,VS The default number of alignments is 8,short Variables of type account for 2 byte , The alignment number is 2,2 and 8 comparison 2 smaller , This short The variable of type will be offset from The integer multiple of the default alignment number That is, the offset is 4(2×2) The location begins to store , The occupation offset is 4、5 These two bytes .
(3) The storage of the third element ,VS The default number of alignments is 8,int Variables of type account for 4 byte , The alignment number is 4,4 and 8 comparison 4 smaller , This int The variable of type will be offset from an integer multiple of the default alignment number, that is, the offset is 8(4×2) The location begins to store , The occupation offset is 8、9、10、11 These four bytes .
(4) The storage of the fourth element ,VS The default number of alignments is 8,char Variables of type account for 1 byte , The alignment number is 1,1 and 8 comparison 1 smaller , This char The variable of type will be offset from an integer multiple of the default alignment number, that is, the offset is 12(1×12) The location begins to store , The occupation offset is 12 This one byte .
(5) All elements are stored , The size of the whole structure is an integer multiple of the maximum value of the alignment number of all variables ( Remove the system default alignment number ). The default alignment number of variables here is int ->4,
short ->2 ,int ->4 ,char ->1, The maximum value is 4, The data storage of the whole structure occupies 13 Bytes , Only 16(4×4) It can cover all the... Used to store variables 13 Bytes , Finally, the size of the structure is 16 Bytes .
Then we analyze struct B:
(1) The first element is stored at an offset of 0 The address of ,int Variables of type account for 4 byte , It will occupy an offset of 0、1、2、3 These four bytes .
(2) The storage of the second element needs to consider the default alignment number ,VS The default number of alignments is 8,short Variables of type account for 2 byte , The alignment number is 2,2 and 8 comparison 2 smaller , This short The variable of type will be offset from an integer multiple of the default alignment number, that is, the offset is 4(2×2) The location begins to store , The occupation offset is 4、5 These two bytes .
(3) The storage of the third element ,VS The default number of alignments is 8,char Variables of type account for 1 byte , The alignment number is 1,1 and 8 comparison 1 smaller , This char The variable of type will be offset from an integer multiple of the default alignment number, that is, the offset is 6(1×6) The location begins to store , The occupation offset is 6 This one byte .
(4) The storage of the fourth element ,VS The default number of alignments is 8,int Variables of type account for 4 byte , The alignment number is 4,4 and 8 comparison 4 smaller , This int The variable of type will be offset from an integer multiple of the default alignment number, that is, the offset is 8(4×2) The location begins to store , The occupation offset is 8、9、10、11 These four bytes .
(5) All elements are stored , The size of the whole structure is an integer multiple of the maximum value of the alignment number of all variables ( Remove the system default alignment number ). The default alignment number of variables here is int ->4, short ->2 ,int ->4 ,char ->1, The maximum value is 4, The data storage of the whole structure occupies 12 Bytes , Only 12(4×3) It can cover all the... Used to store variables 13 Bytes , Finally, the size of the structure is 12 Bytes .

In the figure above, we can clearly observe the storage state of data , But there is also a lot of space wasted .
3. 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 .
struct S1
{
char c1;
int i;
char c2;
};//12
struct S2
{
char c1;
char c2;
int i;
};//8When 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 .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 .
4. Change the default alignment number
We met before #pragma This preprocessing instruction , Here we use again , We can change our default alignment number .
#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()
{
printf("%d\n", sizeof(struct S1));//12
printf("%d\n", sizeof(struct S2));//6
return 0;
}5. Structural parameters
struct S
{
int data[1000];
int num;
};
struct S s = {
{1,2,3,4}, 1000};
void print1(struct S s)
{
printf("%d\n", s.num);
}
void print2(struct S* ps)
{
printf("%d\n", ps->num);
}
int main()
{
print1(s);
// Transmissive structure
print2(&s);
// Address
return 0;
}These two functions can complete the task , But when a function passes parameters , Parameters need to be stacked , 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 , It can lead to performance degradation . Moreover, the content of the variable cannot be changed by transferring the value of the variable , We cannot change the original structure when necessary .
Conclusion : Structure type parameters only pass addresses .
3、 ... and 、 Bit segment
1. summary
Similar to a structure , But the back The number specifies the number of bits occupied by the defined internal variable .
The declaration and structure of a bit segment are similar , There are two differences :
- The member of the segment must be int、unsigned int or signed int .( This box is too dead , In fact, any shaping data can be bit broken , But other data are not often used )
- The member name of the segment is followed by a colon and a number .
struct A
{
int _a:2;//a Although it is an integer variable , But only two bits are stored
int _b:5;// The rest is the same
int _c:10;
int _d:30;
};2. Bit segment memory allocation
- The members of a segment can be int unsigned int signed int Or is it char ( It belongs to the plastic family ) type
- The space of the bit segment is based on 4 Bytes ( int ) perhaps 1 Bytes ( char ) The way to open up .
- Bit segments involve many uncertainties , Bit segments are not cross platform , Pay attention to portable program should avoid using bit segment .
for instance :
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;First , We need to know how these variables allocate space in memory :
(1) First open up a byte space :00000000
(2)a Variables are stored in the last three bits :00000 000->a
(3)b Variables are stored in the last four bits starting from the second bit :0 0000->b 000->a
(4)c The storage of variables requires five bits , There are not enough bits in this byte , Need to open up a byte space again :0 0000->b 000->a 00000000
(5)c Variables are stored in the last five bits :0 0000->b 000->a 000 00000->c
(6)d The storage of variables requires four bits , There are not enough bits in this byte , Need to open up a byte space again :0 0000->b 000->a 000 00000->c 00000000
(7)c Variables are stored in the last five bits :0 0000->b 000->a 000 00000->c 0000 0000->d
(8) Finally, the size of this structure is three bytes , Although some bits have been discarded , But compared with the original, it still saves a lot of space
then , We assign it
(1)10 Convert to binary :1010, But memory only gives three bits , therefore a Can only store 010 That is to say 2
(2)12 Convert to binary :1100, Four bits are given ,b Normal storage
(3)3 Convert to binary :11, But the memory gives five bits ,c Fill zero in the position of normal storage surplus
(4)4 Convert to binary :100, But memory only gives four bits ,d Fill zero in the position of normal storage surplus
Final :0 1100->b 010->a 000 00011->c 0000 0100->d( The address increases from left to right )
3. The cross platform problem of bit segment
- int It's uncertain whether a bit segment is treated as a signed number or an unsigned number .
- 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 A bit of the machine will go wrong )
- 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 .
- 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 . Due to the space saving advantage of bit segment , It can be used for information transmission of network data .
Four 、 enumeration
1. Definition of enumeration
Enumeration, as the name suggests, is to enumerate one by one , hold Possible values are listed one by one .
such as : There are seven days in a week , There are two genders , There are twelve months in a year and so on .
enum Day
{
Mon,
Tues,
Wed,
Thur,
Fri,
Sat,
Sun
};
// week
enum Sex
{
MALE,
FEMALE,
SECRET
};
// Gender As defined above enum Day , enum Sex , enum Color 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 .
enum Day
{
Mon=1,
Tues,
Wed,
Thur,
Fri,
Sat,
Sun
};
// Define the first enumeration constant as 1, The following enumeration constants will also change 2. 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 )4. Easy to debug 5. Easy to use , You can define more than one constant at a time
3. 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; // It's ok 5、 ... and 、 union ( Shared body )
1. Definition of joint type
Union is also a special custom type. The 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 ).
// Declaration of union type
union Un
{
char c;
int i;
};
// The definition of joint variables
union Un un;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 ).
#include<stdio.h>
union Un
{
int i;
char c;
};
int main()
{
union Un un;
printf("%p\n", &(un.i));
printf("%p\n", &(un.c));
printf("%d\n", sizeof(union Un));
return 0;
}
// result :005FF918
//005FF918
//4
Because internal variables share part of the space , So avoid using internal variables at the same time , That's the top char c And int i Can't be used at the same time .
2. 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 .
for example :
#include<stdio.h>
union Un1
{
char c[5];// It can be understood as a five character variable ,5bytes, The data type is char, The alignment number is 1
int i;//4bytes, The data type is int, The alignment number is 4
};
// Similar to a structure , The consortium also has memory alignment .
// So its size is int The integer multiple of the corresponding alignment number , That is to say 8
union Un2
{
short c[7];// It can be understood as seven variables ,14bytes, The data type is short, The alignment number is 2
int i;//4bytes, The data type is int, The alignment number is 4
};
// So its size is int The integer multiple of the corresponding alignment number , That is to say 16
int main()
{
printf("%d\n", sizeof(union Un1));//8
printf("%d\n", sizeof(union Un2));//16
return 0;
}Structure 、 Enumeration and union ends
边栏推荐
- 移动web布局方法
- 数据库清空表数据并让主键从1开始
- redis源码 -ziplist
- Do you still have certificates to participate in the open source community?
- Open source SPL enhances mangodb computing
- [today in history] July 1: the father of time-sharing system was born; Alipay launched barcode payment; The first TV advertisement in the world
- Chapter VI modified specification (SPEC) class
- Myormframeworkjdbc review and problem analysis of user-defined persistence layer framework, and thought analysis of user-defined persistence layer framework
- 网络RTK无人机上机测试[通俗易懂]
- The uniapp project starts with an error binding Node is not a valid Win32 Application ultimate solution
猜你喜欢

Kubernetes进阶部分学习笔记

How much memory does bitmap occupy in the development of IM instant messaging?

Volcanic engine Xiang Liang: machine learning and intelligent recommendation platform multi cloud deployment solution officially released
![[onnx] export pytorch model to onnx format: support multi parameter and dynamic input](/img/bd/e9a1d3a2c9343b75dbae5c7e18a87b.png)
[onnx] export pytorch model to onnx format: support multi parameter and dynamic input

Card link
![[cloud native | learn kubernetes from scratch] VIII. Namespace resource quotas and labels](/img/7e/2bdead512ba5bf5ccd0830b0f9b0f2.png)
[cloud native | learn kubernetes from scratch] VIII. Namespace resource quotas and labels

Online XML to JSON tool

增加 swap 空间
![[today in history] July 15: Mozilla foundation was officially established; The first operation of Enigma cipher machine; Nintendo launches FC game console](/img/7d/7a01c8c6923077d6c201bf1ae02c8c.png)
[today in history] July 15: Mozilla foundation was officially established; The first operation of Enigma cipher machine; Nintendo launches FC game console

参与开源社区还有证书拿?
随机推荐
test
103. (cesium chapter) cesium honeycomb diagram (square)
Socket error Event: 32 Error: 10053. Connection closing...Socket close
MySQL 日期【加号/+】条件筛选问题
RF、GBDT、XGboost特征选择方法「建议收藏」
[today in history] June 28: musk was born; Microsoft launched office 365; The inventor of Chua's circuit was born
10.< tag-动态规划和子序列, 子数组>lt.53. 最大子数组和 + lt.392. 判断子序列 dbc
[today in history] June 29: SGI and MIPS merged; Microsoft acquires PowerPoint developer; News corporation sells MySpace
Chinese son-in-law OTA Ono became the first Asian president of the University of Michigan, with an annual salary of more than 6.5 million!
【高等数学】【1】函数、极限、连续
Array of sword finger offer question bank summary (I) (C language version)
每条你收藏的资讯背后,都离不开TA
[advanced mathematics] [8] differential equation
qml 结合 QSqlTableModel 动态加载数据 MVC「建议收藏」
redis源码 -ziplist
Mobile web layout method
During the interview, I was asked how to remove the weight of MySQL, and who else wouldn't?
[today in history] July 18: Intel was founded; The first photo was posted on the world wide web; EBay spins off PayPal
Cloud native, Intel arch and cloud native secret computing three sig online sharing! See you today | issues 32-34
[today in history] June 30: von Neumann published the first draft; The semiconductor war in the late 1990s; CBS acquires CNET
