当前位置:网站首页>[user defined type] structure, union, enumeration
[user defined type] structure, union, enumeration
2022-07-07 00:49:00 【RookieStriver】
Before we learn C When it comes to language , There are several custom types that we need to master , Then I also share my understanding based on my own learning . Hope to learn from each other , Common progress !
List of articles
One : Structure
1.1: The basics 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 .
1.2: Statement of structure
struct tag
{
member-list;
}variable-list;// Global variables
For example, describe a student :
struct Stu
{
char name[20];//mingzi
int age;//nianlin
char sex[2];//xingbie
char id[20];//xuehao
1.3: Special statement
When declaring a structure . It can be stated incompletely .
For example, anonymous structure type .
struct
{
int a;
char b;
float c;
}x;
struct
{
int a;
char b;
float c;
}a[20], *p;
The above two structures omit the structure label when declaring (tag).
So here comes the question ?
p = &x; Is it legal ?
Warning : The compiler will treat the above two declarations as two completely different types , So it's illegal .
1.4: Self reference of structure
Can you include a member whose type is the structure itself ?
struct Node
{
int data;
struct Node next;
};
This kind of self quotation is not feasible !
The following is the correct way of self reference :
struct Node
{
int data;
struct Node * next;// Pointer type of structure
};
1.5: Structure variable definition and initialization
struct Point
{
int x;
int y;
}p1;// Define global variables while declaring types p1;
struct Point p2;// Define structure variables p2;
// initialization : Define variables and assign initial values at the same time 、
struct Point p3 = {
x, y};
1.6: Structure memory alignment
We have mastered the basic use of structures , Now let's discuss the size of the structure
int main()
{
struct s1
{
char c1;
int i;
char c2;
};
printf("%d\n", sizeof(struct s1));//12
struct s2
{
char c1;
char c2;
int i;
};
printf("%d\n", sizeof(struct s2));//8
struct s3
{
double d;
char c;
int i;
};
printf("%d\n", sizeof(struct s3));//16
struct s4
{
char c1;
struct s3 S3;
int i;
};
printf("%d\n", sizeof(struct s4));//32
system("pause");
return 0;
}
How to calculate the structure size ?
First, you have to master the alignment rules of the structure :
1: The first member is associated with the structure variable The offset for the 0 The address of .
2: Other member variables should be aligned to Align numbers An integral multiple of the address of .
Align numbers = The compiler defaults to an 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 An integer multiple of the maximum number of alignments .
4: 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 ( Includes the number of alignments for nested structures ) Integer multiple .
Why memory alignment exists ?
On the whole, it's : Memory alignment of structures is a way of trading space for time !
So when designing structures , We have to satisfy the alignment , And save space **, Then let the members who occupy less space gather together as much as possible .**
1.7: Change the default alignment number
We met before #pragma This preprocessing instruction , We use... Again , We can change our default alignment number .
#pragma pack(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));//12
printf("%d\n", sizeof(struct s2));//6
system("pause");
return 0;
}
Conclusion : When the structure is not aligned properly , We can change the default alignment number ourselves .
1.8: 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(struct S * ps)
{
printf("%d\n", ps->num);
}
int main()
{
print1(s);// Transmissive structure
print2(&s);// Pass structure address
system("pause");
return 0;
}
above print1 and print 2 Which function is better ?
The answer is : The preferred print2 function
reason : 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 large , Leading to performance degradation .
Conclusion : When structures transmit parameters , To transfer the address of the structure .
Two : Bit segment
2.1: What is a bit segment
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, short.
- The member name of the bit field is followed by A colon and a number .
such as :
struct A
{
int a : 2;
int b : 5;
int c : 10;
int d : 30;
};
int main()
{
printf("%d\n", sizeof(struct A));//8
system("pause");
return 0;
}
A It's a bit segment type , What is the size of that segment ?
understand : The space of the bit segment is based on 4 Bytes (int) perhaps 1 Bytes (char) To open up , The number after the member represents Needed bit Bit size .
2.2: Bit segment memory allocation
- The members of a segment can be int,unsigned int,signed int, perhaps char( It belongs to the integer family ) type .
- The space of the bit segment is based on 4 Bytes (int) perhaps 1 Bytes (char) To open up .
- 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;
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 space is opened up ?
2.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).
- 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. Good space saving , But there are cross platform problems .
3、 ... and : enumeration
Enumeration, as the name suggests, is an example , List the possible values .
3.1: Definition of enumeration type
enum Day
{
Mon,
Tues,
Wed,
Thur,
Fri,
Sat,
Sun
};
enum Sex
{
MALE,
FEMALE,
SECRET
};
As defined above enum Day,enum Sex, All enumeration types .{} The contents in are possible values of enumeration types , Also known as enumeration constants . These default values have values . The default from the 0 Start , In turn, increasing 1, Of course, initial values can also be assigned when defining .
for example :
enum Color
{
red = 1,
Green = 2,
Blue = 4
};
3.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 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.3: Use of enumeration
enum Color
{
Red = 1,
Green = 2,
Blue = 4
};
int main()
{
enum Color clr = Green;
system("pause");
return 0;
}
Be careful : Enumeration variables can only be assigned with enumeration constants , There will be no type difference .
Four : 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 characteristic is that these members Share the same space .
union Un
{
char c;
int i;
};
int main()
{
union Un un;// The definition of joint variables
printf("%d\n", sizeof(un));// Calculate the size of the joint variable
system("pause");
return 0;
}
4.2 Characteristics of Union
The members of a union are spaces that share the same memory , 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
{
char c;
int i;
};
int main()
{
union Un un;
printf("%d\n", &(un.i));
printf("%d\n", &(un.c));
system("pause");
return 0;
}
4.3: 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 .
union Un1
{
char c[5];
int i;
};
union Un2
{
char c[7];
int i;
};
int main()
{
printf("%d\n", sizeof(union Un1));// Size is 8
printf("%d\n", sizeof(union Un2));// Size is 16
system("pause");
return 0;
}
We have the above pairs of structures , Bit segment , union , Enumerating these user-defined types makes a basic interpretation , If you have gained something, I hope to give a wave of support to the third company , Please also point out any comments or suggestions in the comment area , Thank you. !
边栏推荐
- Js+svg love diffusion animation JS special effects
- The way of intelligent operation and maintenance application, bid farewell to the crisis of enterprise digital transformation
- AI super clear repair resurfaces the light in Huang Jiaju's eyes, Lecun boss's "deep learning" course survival report, beautiful paintings only need one line of code, AI's latest paper | showmeai info
- 深度学习之线性代数
- 接口(接口相关含义,区别抽象类,接口回调)
- 英雄联盟|王者|穿越火线 bgm AI配乐大赛分享
- Operation test of function test basis
- 【vulnhub】presidential1
- On February 19, 2021ccf award ceremony will be held, "why in Hengdian?"
- Leecode brush questions record sword finger offer 43 The number of occurrences of 1 in integers 1 to n
猜你喜欢
Threejs image deformation enlarge full screen animation JS special effect
File and image comparison tool kaleidoscope latest download
uniapp中redirectTo和navigateTo的区别
Service asynchronous communication
Everyone is always talking about EQ, so what is EQ?
[software reverse - solve flag] memory acquisition, inverse transformation operation, linear transformation, constraint solving
Article management system based on SSM framework
Memory optimization of Amazon memorydb for redis and Amazon elasticache for redis
Idea automatically imports and deletes package settings
Win10 startup error, press F9 to enter how to repair?
随机推荐
Advanced learning of MySQL -- basics -- basic operation of transactions
Slam d'attention: un slam visuel monoculaire appris de l'attention humaine
C9 colleges and universities, doctoral students make a statement of nature!
Explain in detail the implementation of call, apply and bind in JS (source code implementation)
Interface (interface related meaning, different abstract classes, interface callback)
学习使用代码生成美观的接口文档!!!
Testers, how to prepare test data
Chapter II proxy and cookies of urllib Library
Clipboard management tool paste Chinese version
Threejs image deformation enlarge full screen animation JS special effect
threejs图片变形放大全屏动画js特效
How to get started and improve test development?
fastDFS数据迁移操作记录
Advantages and disadvantages of code cloning
【软件逆向-求解flag】内存获取、逆变换操作、线性变换、约束求解
三维扫描体数据的VTK体绘制程序设计
Matlab learning notes
Leecode brush question record sword finger offer 56 - ii Number of occurrences of numbers in the array II
【YoloV5 6.0|6.1 部署 TensorRT到torchserve】环境搭建|模型转换|engine模型部署(详细的packet文件编写方法)
Memory optimization of Amazon memorydb for redis and Amazon elasticache for redis