当前位置:网站首页>[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. !
边栏推荐
- 【软件逆向-自动化】逆向工具大全
- Clipboard management tool paste Chinese version
- Leecode brush questions record sword finger offer 11 Rotate the minimum number of the array
- Leetcode (547) - number of provinces
- JWT signature does not match locally computed signature. JWT validity cannot be asserted and should
- Advantages and disadvantages of code cloning
- Advanced learning of MySQL -- basics -- multi table query -- inner join
- Data analysis course notes (V) common statistical methods, data and spelling, index and composite index
- Advanced learning of MySQL -- basics -- multi table query -- self join
- Operation test of function test basis
猜你喜欢
Slam d'attention: un slam visuel monoculaire appris de l'attention humaine
System activity monitor ISTAT menus 6.61 (1185) Chinese repair
threejs图片变形放大全屏动画js特效
Lombok 同时使⽤ @Data 和 @Builder 的坑,你中招没?
Everyone is always talking about EQ, so what is EQ?
48页数字政府智慧政务一网通办解决方案
JWT signature does not match locally computed signature. JWT validity cannot be asserted and should
深度学习之线性代数
Attention SLAM:一種從人類注意中學習的視覺單目SLAM
Data analysis course notes (III) array shape and calculation, numpy storage / reading data, indexing, slicing and splicing
随机推荐
JWT signature does not match locally computed signature. JWT validity cannot be asserted and should
准备好在CI/CD中自动化持续部署了吗?
Geo data mining (III) enrichment analysis of go and KEGG using David database
Learn to use code to generate beautiful interface documents!!!
Meet the level 3 requirements of ISO 2.0 with the level B construction standard of computer room | hybrid cloud infrastructure
Leecode brushes questions and records interview questions 01.02 Determine whether it is character rearrangement for each other
The way of intelligent operation and maintenance application, bid farewell to the crisis of enterprise digital transformation
Lombok 同时使⽤ @Data 和 @Builder 的坑,你中招没?
How to get started and improve test development?
Cross-entrpy Method
37 page overall planning and construction plan for digital Village revitalization of smart agriculture
MySQL learning notes (mind map)
Advanced learning of MySQL -- basics -- multi table query -- external connection
Zynq transplant ucosiii
Core knowledge of distributed cache
C9高校,博士生一作发Nature!
Memory optimization of Amazon memorydb for redis and Amazon elasticache for redis
Encryption algorithm - password security
stm32F407-------DAC数模转换
2022/2/10 summary