当前位置:网站首页>Custom type: structure, enumeration, union
Custom type: structure, enumeration, union
2022-07-04 09:47:00 【skeet follower】
Catalog
1. Declaration of structure type
1.1 Basic knowledge of structure
2. Self reference of structure
3. Structure variable definition and initialization
4.1 Rules for structure memory alignment
4.2 Calculation of structure size
4.4 Change the default alignment number
6.2 Bit segment memory allocation
6.3 The cross platform problem of bit segment
One . Structure
1. Declaration of structure type
1.1 Basic knowledge 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 Stu
{
char name[20];// name
int age;// Age
char sex[5];// Gender
char id[20];// Student number
};// You can't lose the semicolon 1.3 Special statement
// Anonymous struct type
struct
{
int a;
char b;
float c; }x;
struct
{
int a;
char b;
float c; }a[20], *p;// Based on the above code , Is the following code legal ?p = &x;
struct Book{
char author[20];
char name[20];
int price;
}b1,b2;// overall situation
struct Book b3;// overall situation
int main(){
struct Book b4;// Local
return 0;
}there b1,b2,b3,b4 The expression meaning is the same, but some are global variables , Some are local variables .
2. Self reference of structure
In the data structure, there are sequential storage and chain storage , Sequential storage is continuous and easy to operate , And chain storage is not continuous. We need to find a way to put it " strand “ Just get up .

Look at the code 1 Is it feasible :
struct Node
{
int data;
struct Node next;
}; Obviously, this will lead to infinite recursive search, which is wrong . In fact, we can use pointers to solve this problem by storing part of the data and part of the address , The correct code is as follows :
struct Node
{
int data;
struct Node* next;
}; Note that writing code like this is not feasible :
// Code 3
typedef struct
{
int data;
Node* next; }Node;
// Write code like this , Is it feasible ?
// Solution :
typedef struct Node
{
int data;
struct Node* next; }Node;3. Structure variable definition and initialization
struct Point{
int x;
int y;
}p1={1,2},p2={3,4};// overall situation
struct Point p3={5,6};// overall situation
struct S{
double d;
struct Point p;
}
int main()
{
struct Point p4={7,8};// Local
struct S s={3.14,{1,5}};// Structure contains structure initialization
return 0;
}4. Structure memory alignment 4.1 Rules for structure memory alignment
1. Structure of the The first member Always place it at the beginning of the structure with an offset of 0 The location of .
2. Structure members from The second member Start , Always put an offset of Align numbers At an integral multiple of .( Align numbers = The compiler's default alignment number and the smaller value of the variable's own size ,VS The next general alignment number is 8)
3. The total size of the structure must be an integral multiple of the largest alignment number of each member .
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 the maximum number of alignments ( The number of alignments with nested structures ) Integer multiple .
4.2 Calculation of structure size
struct S1
{
char c1;
int i;
char c2;
};
printf("%d\n", sizeof(struct S1));
struct S2
{
char c1;
char c2;
int i;
};
printf("%d\n", sizeof(struct S2));
Nested structure
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;
};
printf("%d\n", sizeof(struct S4));
4.3 Memory alignment reason
1. Platform reasons ( Reasons for transplantation ):Not all hardware platforms can access any data on any address ; Some hardware platforms can only be at certain addressesTo retrieve certain types of data , Otherwise, a hardware exception will be thrown .2. 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 , processorTwo memory accesses are required ; The aligned memory access only needs one access .
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 S1
{
char c1;
int i;
char c2;
};
struct S2
{
char c1;
char c2;
int i;
};4.4 Change the 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 5 Structural parameters
struct S {
int data[1000];
int num;
};
// Structural parameters
void print1(struct S m) {
int i = 0;
for (i = 0; i < 10; i++) {
printf("%d ", m.data[i]);
}
printf("\nnum=%d\n", m.num);
}
// Structure address transfer parameter
void print2(struct S* m) {
int i = 0;
for (i = 0; i < 10; i++) {
printf("%d ", m->data[i]);
}
printf("\nnum=%d\n", m->num);
}
int main()
{
struct S s = { {1,2,3,4,5,6,7,8,9,10},20 };
print1(s);
print2(&s);
return 0;
}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 .
6 Structural position segment
6.1 What is a bit segment
The declaration and structure of a bit segment are similar , There are two differences :1. The member of the segment must be int、unsigned int or signed int .2. The member name of the segment is followed by a colon and a number .
for example :
struct A {
int _a:2;
int _b:5;
int _c:10;
int _d:30;
};
printf("%d\n", sizeof(struct A));6.2 Bit segment memory allocation
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;

6.3 The cross platform problem of bit segment
1. int It's uncertain whether a bit segment is treated as a signed number or an unsigned number .2. 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 .3. 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 .4. When a structure contains two bit segments , The second segment is relatively large , Cannot hold the remaining bits of the first bit segment , Is to discard the remaining bitsOr use , This is uncertain .
Two . enumeration
1. Enumeration Definition
As the name suggests, enumeration is enumeration , List all the possibilities .
The code is as follows :
enum Day// week
{
Mon,
Tues,
Wed,
Thur,
Fri,
Sat,
Sun
};
enum Sex// Gender
{
MALE,
FEMALE,
SECRET
};enum Color// Color
{
RED=1,
GREEN=2,
BLUE=4
};2. Advantages of enumeration
1. Increase the readability and maintainability of the code2. and #defifine The defined identifier comparison enumeration has type checking , More rigorous .3. Prevent named pollution ( encapsulation )4. Easy to debug5. Easy to use , You can define more than one constant at a time
3、 ... and . Consortium
1. Definition of joint type
// Declaration of union type
union Un
{
char c;
int i;
};
// The definition of joint variables
union Un un;
// Calculate the size of the variables
printf("%d\n", sizeof(un));//42. Characteristics of Union
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 must have at leastThe member with the greatest ability to save )

3. Calculation of joint size
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 .such as :
union Un1
{
char c[5]; //5 1
int i;//4 4
};
union Un2
{
short c[7]; //14 2
int i; // 4 4
};
// What is the output below ?
printf("%d\n", sizeof(union Un1)); //8
printf("%d\n", sizeof(union Un2));//16边栏推荐
- 2022-2028 global optical transparency industry research and trend analysis report
- PHP is used to add, modify and delete movie information, which is divided into foreground management and background management. Foreground users can browse information and post messages, and backgroun
- C语言指针面试题——第二弹
- Global and Chinese market of air fryer 2022-2028: Research Report on technology, participants, trends, market size and share
- Golang 类型比较
- Write a jison parser from scratch (2/10): learn the correct posture of the parser generator parser generator
- lolcat
- Exercise 9-5 address book sorting (20 points)
- System. Currenttimemillis() and system Nanotime (), which is faster? Don't use it wrong!
- 2022-2028 global gasket metal plate heat exchanger industry research and trend analysis report
猜你喜欢

智能网关助力提高工业数据采集和利用

mmclassification 标注文件生成

智慧路灯杆水库区安全监测应用

Hands on deep learning (44) -- seq2seq principle and Implementation

品牌连锁店5G/4G无线组网方案

C language pointer classic interview question - the first bullet

直方图均衡化

el-table单选并隐藏全选框

C # use gdi+ to add text to the picture and make the text adaptive to the rectangular area

技术管理进阶——如何设计并跟进不同层级同学的绩效
随机推荐
Hands on deep learning (38) -- realize RNN from scratch
Get the source code in the mask with the help of shims
PHP student achievement management system, the database uses mysql, including source code and database SQL files, with the login management function of students and teachers
C语言指针经典面试题——第一弹
智能网关助力提高工业数据采集和利用
回复评论的sql
Modules golang
Global and Chinese market of bipolar generators 2022-2028: Research Report on technology, participants, trends, market size and share
SQL replying to comments
How to batch change file extensions in win10
libmysqlclient. so. 20: cannot open shared object file: No such file or directory
Deadlock in channel
Problems encountered by scan, scanf and scanln in golang
Hands on deep learning (33) -- style transfer
Hands on deep learning (37) -- cyclic neural network
Global and Chinese markets of thrombography hemostasis analyzer (TEG) 2022-2028: Research Report on technology, participants, trends, market size and share
Explanation of for loop in golang
DR6018-CP01-wifi6-Qualcomm-IPQ6010-IPQ6018-FAMILY-2T2R-2.5G-ETH-port-CP01-802-11AX-MU-MIMO-OFDMA
Hands on deep learning (32) -- fully connected convolutional neural network FCN
How do microservices aggregate API documents? This wave of show~