当前位置:网站首页>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
边栏推荐
- Is QQ 32-bit or 64 bit software (where to see whether the computer is 32-bit or 64 bit)
- 第六章 修改规范(SPEC)类
- 【高等数学】【5】定积分及应用
- [Infographics Show] 248 Public Domain Name
- FormatDateTime说解[通俗易懂]
- 9. < tag dynamic programming and subsequence, subarray> lt.718. Longest repeated subarray + lt.1143. Longest common subsequence
- 每条你收藏的资讯背后,都离不开TA
- [today in history] July 2: BitTorrent came out; The commercial system linspire was acquired; Sony deploys Playstation now
- “链”接无限可能:数字资产链,精彩马上来!
- Remote monitoring solution of intelligent electronic boundary stake Nature Reserve
猜你喜欢
![[today in history] July 13: the father of database passed away; Apple buys cups code; IBM chip Alliance](/img/2d/c23a367c9e8e2806ffd5384de273d2.png)
[today in history] July 13: the father of database passed away; Apple buys cups code; IBM chip Alliance

Working principle of radar water level gauge and precautions for installation and maintenance

Embedded development: embedded foundation -- threads and tasks

Clickhouse notes 02 -- installation test clickvisual
![[tensorrt] dynamic batch reasoning](/img/59/42ed0074de7162887bfe2c81891e20.png)
[tensorrt] dynamic batch reasoning

Key network protocols in tcp/ip four layer model

「分享」DevExpress ASP.NET v22.1最新版本系统环境配置要求
![[advanced mathematics] [6] differential calculus of multivariate functions](/img/9e/84fe6f74b58cbaabab1b6eed0df556.png)
[advanced mathematics] [6] differential calculus of multivariate functions

【ONNX】pytorch模型导出成ONNX格式:支持多参数与动态输入

Leetcode customs clearance: hash table six, this is really a little simple
随机推荐
Question and answer 47: geeks have an appointment - the current monitoring system construction of CSC
Online random coin tossing positive and negative statistical tool
SecureCRT garbled code solution [easy to understand]
股票软件开发
Formatdatetime explanation [easy to understand]
Vivo official website app full model UI adaptation scheme
预处理指令
使用cookie登录百度网盘(网站使用cookie)
[Infographics Show] 248 Public Domain Name
【高等数学】【4】不定积分
Vulnhub | dc: 6 | [actual combat]
LeetCode通关:哈希表六连,这个还真有点简单
103. (cesium chapter) cesium honeycomb diagram (square)
QML combines qsqltablemodel to dynamically load data MVC "recommended collection"
Socket error Event: 32 Error: 10053. Connection closing...Socket close
【NOI模拟赛】字符串匹配(后缀自动机SAM,莫队,分块)
[tensorrt] dynamic batch reasoning
Kubernetes advanced part learning notes
Chapter VI modified specification (SPEC) class
各厂商网络虚拟化的优势
