当前位置:网站首页>Advanced C language (11) - user defined data types
Advanced C language (11) - user defined data types
2022-07-25 08:00:00 【Not yet】
Catalog
- Preface
- 1. Structure
- 2. Bit segment - Structure expansion
- 3. enumeration - Enumerable constants
- 4. union ( Shared body )
- Conclusion
Preface
C The language itself contains many data types , But it can't always meet the needs . Custom types allow users to create specific and appropriate types . This paper mainly introduces the structure 、 Bit segment 、 Enumeration and union .
1. Structure
A structure is a collection of values , These values can be of the same type , It can be different , Member variables called structs . Similar to array but different . Structs are commonly used custom types .
1.1 Declaration of a structure
keyword struct
General statement
struct tag{
// Structural tag ( Structure name struct tag)
member_list;// Structure member list
}veriable_list;// Structure variable list ( There can be no )
for example The structural type of information describing a student :
struct student{
char name[20];// The student's name
char num[15];// Student student id
double score;// Student average
};
Implicitly declare
Implicitly declare : Omit the structure declaration of the structure label .
struct {
member_list;// Structure member list
}veriable_list;// Structure variable list
- The implicitly declared structure has no name Variables can only be defined when declared , Variables cannot be defined later .
- Each implicitly declared struct type is different Of , Even if the member variables are exactly the same .
for example :
#include <stdio.h>
struct {
int a;
char b;
}c;
struct {
int a;
char b;
}*p;
int main() {
p = &c;// Implicit type conversion occurs here
return 0;
}
1.2 Self reference of structure
In a structure Contains itself ( Structure ) The pointer to As a member of the structure .
struct tag{
int data;
struct tag* next;
};
Use typedef Rename the structure
Write it correctly :
typedef struct Node{
int data;
struct Node* next;
}Node;
Wrong writing :
typedef struct Node{
int data;
Node* next;
}Node;
// Here is to rename the structure to Node Reuse Node* next As a structural member variable ; Use first Node*next As a structural member variable, the structural weight is named Node. These two explanations will produce inconsistencies .
1.3 Structure variable definition and initialization
Define variables and initialize variables while declaring the structure
struct student{
char name[20];// full name
int num;// Student number
}s1;// Structural variable s1 The definition of
//-------------------------------
struct student{
char name[20];// full name
int num;// Student number
}s1, s2 = {
"sunwukong", 1001};// Structural variable s1、s2 Definition and s2 The initialization
//--------------------------------
struct Node
{
int data;
struct student s;
struct Node* next;
}n = {
10, {
"tangsheng", 1002}, NULL};// Structure nested definition and initialization
First declare the structure type before defining variables and initializing variables
struct student{
char name[20];// full name
int num;// Student number
};
struct student s1;// Structural variable s1 The definition of
//------------------------------
struct student{
char name[20];// full name
int num;// Student number
};
struct student s1;// Structural variable s1 The definition of
struct student s2 = {
"sunwukong", 1001};// Structural variable s2 Definition and s2 The initialization
//------------------------------
struct Node
{
int data;
struct student s;
struct Node* next;
};
struct Node n = {
10, {
"tangsheng", 1002}, NULL};// Structure nested definition and initialization
1.4 The size of the structure variable - Structure memory alignment
A structure is a collection of values , When defining a structural variable , In memory, a continuous memory space will be allocated as the space for structural variables . So how big is this continuous space , Here, we need to know the size of structure variables correctly until we have the knowledge of structure memory alignment .
Structure alignment rules
- The first member is offset from the structure variable by 0 The address of .
- Other members should be aligned to a number ( Align numbers ) An integral multiple of the address of .
The number of alignments of a member = Compiler default alignment number ( If any ) A smaller value than the size of the member .
visual studio 2019 The compiler default alignment number is 8.
3. The total size of the structure is an integer multiple of the maximum number of alignments of all member variables .
3. If the structure is nested , The nested structure is aligned to an integral multiple of its maximum alignment , The overall size of the structure variable is the maximum number of alignments ( The number of alignments with nested structures ) Integer multiple .
Example :
- Two structures with the same member , But the different order of members will also lead to different sizes of structure variables .
- If the memory occupied by structure members is small, putting them in front will make the size of structure variables smaller .
#include <stdio.h>
struct S1{
char c1;
int i;
char c2;
};
struct S2
{
char c1;
char c2;
int i;
};
int main() {
printf("%d\n", sizeof(struct S1));
printf("%d\n", sizeof(struct S2));
return 0;
}

Running results :
The size of the nested structure :
#include <stdio.h>
struct S1 {
char c1;
int i;
char c2;
};
struct S2
{
char c1;
struct S1 s2;
double d;
};
int main() {
printf("%d\n", sizeof(struct S2));
return 0;
}

Running results :
Causes of memory alignment
- Platform reasons
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 occurs .
- Performance reasons
data structure ( Especially stacks ) It should be aligned on the natural boundary as much as possible . Because to access misaligned memory , The processor needs two memory accesses ; Aligned memory requires only one access .
This is a Space for time Methods .
When defining the structure type, let Member variables that take up small space should be concentrated together as much as possible , Used to reduce the waste of space caused by memory alignment .
Change the default alignment number
#pragma yes Preprocessing instruction ,#pragma pack() Sure modify The code behind it The default number of alignments ( If any ), Until it appears again #pragma pack() End the modification of the default alignment number .
#include <stdio.h>
#pragma pack(4)// 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()
{
// What is the result of the output ?
printf("%d\n", sizeof(struct S1));
printf("%d\n", sizeof(struct S2));
return 0;
}
Running results :
1.5 Structural parameters
Pass value ( Structure )
#include <stdio.h>
struct student {
char name[20];
int num;
};
void Print(struct student stu) {
printf("%s %d\n", stu.name, stu.num);
}
int main() {
struct student s = {
"sunwukong", 10001 };
Print(s);
return 0;
}
Running results :
Address
#include <stdio.h>
struct student {
char name[20];
int num;
};
void Print(const struct student* p) {
printf("%s %d\n", p->name, p->num);
}
int main() {
struct student s = {
"sunwukong", 10001 };
Print(&s);
return 0;
}
Running results :
When address transfer and value transfer call can complete the task , Address passing call is better than value passing call .
- Because when a function passes parameters , Parameters need to be stacked , There will be time and space overhead .
- When passing a structure object , If the structure is too large , The system overhead of parameter stack pressing will also be large , It will lead to performance degradation .
When the structure passes parameters Primary address .
2. Bit segment - Structure expansion
The structure has implementation Bit segment The ability of . That is to say, they are similar .
2.1 Initial recognition segment
Declaration of bit segment
Similar to structure declaration , There are different :
- Bit segment Members can only be members of integer families ( Include char);
- After the member of the bit segment There is a colon and a number . This number indicates that the member accounts for A few of the memory bit( position ).
struct S{
int a:2;
int b:4;
int c:16;
};
2.2 Bit segment memory allocation
- Members of the bit segment belong to the plastic family , Such as
int、unsigned int、signed int、char.- The space of the bit segment is four bytes as needed
intOr a bytecharThe way to open up .- Bit segments involve many uncertainties , It's not cross platform , Pay attention to portable program should avoid using bit segment .
visual studio 2019 Example of bit space development under
#include <stdio.h>
struct S
{
char a : 3;
char b : 4;
char c : 5;
char d : 4;
};
int main() {
struct S s = {
0 };
s.a = 10;
s.b = 12;
s.c = 3;
s.d = 4;
printf("%d\n", sizeof(s));
return 0;
}


2.3 The cross platform problem of bit segment
- Bit segment
intyes Whether there is a sign or no sign is undefined , As usualintThere are symbolic differences .- 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) If the largest bit is 25 So in 16 Failed to compile on bit machine , stay 32 Normal operation on bit machine .
- 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 segment members , The second segment is relatively large , When the remaining bits of the first bit segment cannot accommodate the members of the second bit segment , Whether to discard the remaining bits or use them is uncertain .
Compared with structure , Bit segments can achieve the same effect , But it can save space , There are only cross platform problems .
The cross platform problem is not that programs containing bit segments cannot cross platform , Just say yes Write the bit segment code suitable for the platform .
2.4 Application of bit segment
Reduce packet size in the network .
3. enumeration - Enumerable constants
enumeration , seeing the name of a thing one thinks of its function You can list them one by one , And it's a constant .
There are many things in life that can be enumerated one by one : week 、 Month, etc ……
3.1 Definition of enumeration type
Similar to the structure :
keyword enum
enum tag{
// label ( Enum name enum tag)
constant_list,// Enumeration constants - That is, the possible values of enumeration types
}veriable_list;// Enumerate variables () There can be no
- Enumerating constants has values , These values Default from 0 Began to increase , Between adjacent enumeration constants Default Difference between 1.
- It's fine too Assign initial values to enumeration constants , In this way, the value of the assigned enumeration constant and subsequent enumeration constants will change with the initial value , It was still the default value .
Example :
#include <stdio.h>
enum color {
RED,//0
ORANGE,//1
YELLOW,//2
GREEN,//3
CYAN = 10,//10
BLUE,//11
PURPLE//12
}c1;// Enumerate variables c1 The definition of
int main() {
c1 = RED;
enum color c2 = BLUE;// Enumerate variables c2 Definition and initialization of
printf("%d\n", c1);
printf("%d\n", c2);
return 0;
}
3.2 Advantages of enumeration
#define You can also define constants , Achieve the same effect as enumeration . But enumerations compare in this function #define It has several advantages :
- Increase the readability and maintainability of the code ;
- And
#defineCompared with the defined identifier, enumeration has type checking , More rigorous .- Prevent named pollution , Encapsulate constants .
- Easy to debug .
- Easy to use , You can define more than one constant at a time .
3.3 Use of enumeration
#include <stdio.h>
enum week {
MONDAY = 1,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
};
int main() {
enum week a = MONDAY;// Enumerate variables a Store enumeration constants MONDAY, The value is 1
enum week b = 1;// Enumerate variables b Store variables 1, Although the value is 1, But the types don't match , stay c++ Under compilation, you cannot compile .
return 0;
}
4. union ( Shared body )
Similar to structure , however Members share a memory space .
4.1 Definition of joint type
A union type contains a series of members , These members share the same space .
union tag{
// label ( Union name union tag)
member_list;// Member list
}veriable_list;// Variable list ( There can be no )
You cannot initialize a union variable while defining it .
#include <stdio.h>
union un {
int a;
char b;
}c;// Joint variables c The definition of
int main() {
c.a = 10;
union un d;// Joint variables d The definition of .
return 0;
}
4.2 Calculation of joint size
The size of the union is at least the size of the largest member .
When the size of the largest member is not an integer multiple of the maximum alignment number , Will be Align to an integer multiple of the maximum number of alignments .
The maximum number of alignments refers to the structure .
visual studio 2019 give an example
#include <stdio.h>
union Un1 {
char c[5];
int i;
};
union Un2 {
short c[7];
int i;
};
int main() {
printf("%d\n", sizeof(union Un1));
printf("%d\n", sizeof(union Un2));
return 0;
}
union Un1:
char c[5]The size is5Bytes , A single element ischar, Size is1, The default number of alignments is8, So the alignment number is1.iThe size is4Bytes , The default number of alignments is8, So the alignment number is4.- The maximum member size is
5Bytes , The maximum number of alignments is4, So the size of the union is8byte
union Un2:
short c[7]The size is14Bytes , A single element isshort, Size is2, The default number of alignments is8, So the alignment number is2.iThe size is4Bytes , The default number of alignments is8, So the alignment number is4.- The maximum member size is
14Bytes , The maximum number of alignments is4, So the size of the union is16Bytes .
Conclusion
This section mainly introduces the user-defined type related Structure 、 Bit segment 、 enumeration 、 union . Knowing and being familiar with these custom types can help you understand data structure And so on .
END
边栏推荐
- In depth analysis of yolov7 network architecture
- [QNX hypervisor 2.2 user manual]9.3 CPU
- P1086 [NOIP2004 普及组第二题] 花生采摘
- 475-82(230、43、78、79、213、198、1143)
- [unity entry plan] interface Introduction (1) -scene view
- Enq: HW - fault analysis caused by content waiting
- 如何仅用递归函数和栈操作逆序一个栈
- Vs2019 C MFC installation
- IoT物联网嵌入式设备中30种常见传感器模块简介及原理讲解
- Learn when playing No 6 | the magic of document library lies in
猜你喜欢
Technical Analysis | Doris connector combined with Flink CDC to achieve accurate access to MySQL database and table exactly once

Network file storage system (III) practice of fastdfs distributed file system

File details
![[dynamic programming] - Knapsack model](/img/0d/c467e70457495f130ec217660cbea7.png)
[dynamic programming] - Knapsack model
![[unity introduction program] basic concepts - 2D collider collider 2D](/img/cf/a546238a5eaf4707006ecf1b7f19c6.png)
[unity introduction program] basic concepts - 2D collider collider 2D

How to reverse a stack with recursive functions and stack operations only
P1086 [NOIP2004 普及组第二题] 花生采摘

Didi - dispatching

New version 8.6 SEO quick release system (can be built at source level)

A review of nature: gender differences in anxiety and depression - circuits and mechanisms
随机推荐
CSDN custom T-shirts are waiting for you to get, and the benefits of new programmer are coming!
webflux默认io线程数
Kubernetes monitoring component metrics server deployment
A queue of two stacks
Summer Challenge harmonyos - slider slider for custom components
The value of integer a after bitwise negation (~) is - (a+1)
[unity entry plan] interface Introduction (1) -scene view
大佬秋招面经
Programmers can't play at the age of 35. Is it a fact or a misunderstanding?
The difference between batchnorm and layernorm
uiautomator2 常用命令
IoT物联网嵌入式设备中30种常见传感器模块简介及原理讲解
C 43. Get UDP available ports
Implement hot post | community project with timed tasks and cache
How to obtain the intersection / subtraction / Union of two sets by MySQL
Learn when playing No 1 | can live classroom still be like this? Come and unlock "new posture"!
What has become a difficult problem for most people to change careers, so why do many people study software testing?
整数a按位取反(~)后的值为-(a+1)
How should enterprise users choose aiops or APM?
Problems during nanodet training: modulenotfounderror: no module named 'nanodet' solution