当前位置:网站首页>[C language note sharing] custom type: structure, enumeration, Union (recommended Collection)
[C language note sharing] custom type: structure, enumeration, Union (recommended Collection)
2022-07-28 17:45:00 【Crazy orange】
List of articles
- 1. struct Type of structure
- 2 Bit segment
- 3. enumeration
- 4. union ( Shared body )
- 5. practice
1. struct Type of structure
1.1 Basic knowledge of structure
The structure is some
valueSet , thesevalueIt's called a member variable . Each member of a structure can be a variable of a different type .
1.2 Statement of structure
struct tag
{
member_list;// List of member variables
}variable_list;// Structure variable list
for example :

- Type of structure ( Variable name ) It can be a global variable , It can also be a local variable , It depends on the type of structure you create ( Variable name ) The place of
1.3 Special statement ( Anonymous statement )
When you declare the structure , It can be stated incompletely
- for example :


The above structure omits the structure label when declaring (tag).
1.4 Self reference of structure
- The structure contains pointer member variables of its own type
Take a linked list of data structures Example :

errorStructure self reference method of :

Correct structure self reference method :

notes : Anonymous structures cannot self reference !
typedef Name the structure weight

1.5 Structure variable definition and initialization
The definition of structural variables

Initialization of structure variables
- Define variables while initializing

- Structure nesting initialization

1.6 Structure memory alignment ( a key )
( Calculate the size of the structure )
Rules of structure :
The first member is offset from the structure variable by 0 The address of .( The offset of the starting address of the relative data stored in memory )
Other member variables are aligned to a number ( Align numbers ) An integral multiple of the address of .
Align numbers = Compiler default alignment number And
This memberThe size ofSmaller value.
-VS2019 China and Murdoch think 8The 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
All maximum alignments ( The number of alignments with nested structures )Integer multiple
Why is there memory alignment ?
Most of the references are as follows :
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 ( In especialStack) 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 :
The memory alignment of the structure is
SpaceIn exchange forTimeHow to do it .
- 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 .
// for example :
struct Peo
{
char ch;
char p;
int a;
};
1.6.1 Exercises
// practice 1
struct S1
{
char c1;
int i;
char c2;
};
printf("%d\n", sizeof(struct S1));
// practice 2
struct S2
{
char c1;
char c2;
int i;
};
printf("%d\n", sizeof(struct S2));
// practice 3
struct S3
{
double d;
char c;
int i;
};
printf("%d\n", sizeof(struct S3));
// practice 4- Structure nesting problem
struct S4
{
char c1;
struct S3 s3;
double d;
};
practice 1 Explain :c1 Align to 0 At offset ,i Align to 4 At offset ,c2 Align to 8 At offset

Verify whether the explanation is wrong : Offset
offsetof( Return structure members in this type Offset in )

1.7 Change the default alignment number
#pragmaThis preprocessing instruction , You can change the default alignment number
Conclusion : When the structure is not aligned properly , We can change the default alignment number by ourselves .
1.8 Structural parameters
The methods of structure parameter transmission are
1. Pass value
2. Byref
Although there are two ways , But we prefer addressreason: 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 .

2 Bit segment
2.1 What is a bit segment
The declaration and structure of a bit segment are similar , There are two differences :
( The bits of the bit segment are bits )
- The member of the segment must be
int 、unsigned int、 or signed int、char - There is a colon after the member name of the bit segment
:And a number . - Bit segments can only be used in structures
for example :

2.2 Bit segment memory allocation
- The members of a segment can be
int 、unsigned int、 or signed int、char( It belongs to the plastic family ) type - The space of the bit segment is as needed 4 Bytes (
int) perhaps 1 Bytes (char) The way to open up .( For exampleinttype , There is not enough space for storing data , One time development 4 Bytes ) - Bit segments involve many uncertainties , Bit segments are not cross platform , Pay attention to portable program should avoid using bit segment .
- Generally, the members of the bit segment are of the same type , Suggest the same type .
A chestnut :

Bit segment storage , Draw pictures to explain :

2.3 The cross platform problem of bit segment
intIt'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 , However, there are cross platform problems .
3. enumeration
- As the name suggests, it is —— list .
- Take the possible values —— list .
- For example, our real life in :
1. A week's Monday to Sunday is limited 7 God , You can have one List .
2. Gender has : male , Woman 、 A secret , It can also be a One list .
3. Month has 12 Months , You can also list .
3.1 Definition of enumeration type
As defined below
enum Day, Is enumeration type .{}The content of isEnumeration typePossible value of , Also calledEnumeration 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 .

When defining, you can assign an initial value ,
for example :

3.2 Advantages of enumeration
We can use
defineDefine constants , Why do I have to use enumeration ?
Advantages of enumeration :
- Increase the readability and maintainability of the code .
- and
defineDefined identifier comparison enumeration type check , More rigorous . - Prevent naming pollution ( encapsulation ).
- Easy to debug .
- Easy to use , You can define more than one constant at a time .
3.3 Use of enumeration

4. union ( Shared body )
4.1 Definition of joint type
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 :

4.2 Characteristics of Union
Conclusion : Members of the union share the same memory space ( Members have the same address ), 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 ).

4.2.1 Consortium Judge the big and small ends
Concrete realization :

Draw pictures to explain :

4.3 Calculation of the size of the consortium
1. The size of the union is at least the size of the largest member .
2. 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 .

Union memory alignment , Draw pictures to explain :

5. practice
Write a “ Address book program ”.
边栏推荐
猜你喜欢

7-8 浪漫侧影(25分)建树+新解题思路
![[untitled]](/img/86/d284eec4eda6a41676d7455b7ea70b.png)
[untitled]

PCA reports error in eigen (crossprod (t (x), t (x)), symmetric = true): 'x' has infinite value or missing value

【p5.js学习笔记】局部变量(let)与全局变量(var)声明

MySQL高级-MVCC(超详细整理)

mmdetection3D---(1)

Can‘t use an undefined value as an ARRAY reference at probe2symbol

R中因子(factor)

mmdetection3d(2)---结果、log可视化

Public medical database
随机推荐
完全未接触过软件测试的人,培训两个月就可以上岗,真的现实吗?
想转行IT,非科班出身真的不要紧吗?
easyui tree
点云处理---kd-tree
想学习软件测试,零基础去哪里学呢?
【Unity Tilemap】教程 | Basic、Rule Tile、Prefab Brush、Tilemap Collider
Ggplot2 map
In depth sharing of Ali (ant financial) technical interview process, with preliminary preparation and learning direction
JS synchronizes the local time with the server time
Mmcv installation method
R语言 sub()用法
【 R语言—基础绘图】
.net MVC understanding
电工学数字电路自学笔记1.24
Vscode intranet access server
新手通过自学转行软件测试难度大吗?
【Unity Scriptable Object】教程 | 在Unity中使用 Scriptable Object 存储物体数据信息
leetcode系统性刷题(一)-----链表、栈、队列、堆
多线程(线程池ThreadPoolExecutor)
es6 Promise
