当前位置:网站首页>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));//4
2. 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
边栏推荐
- Hands on deep learning (38) -- realize RNN from scratch
- 7-17 crawling worms (15 points)
- `Example of mask ` tool use
- Golang Modules
- Sort out the power node, Mr. Wang he's SSM integration steps
- Hands on deep learning (45) -- bundle search
- Fatal error in golang: concurrent map writes
- Exercise 9-3 plane vector addition (15 points)
- 2022-2028 global probiotics industry research and trend analysis report
- 回复评论的sql
猜你喜欢
C language pointer classic interview question - the first bullet
2022-2028 global edible probiotic raw material industry research and trend analysis report
Baidu R & D suffered Waterloo on three sides: I was stunned by the interviewer's set of combination punches on the spot
The child container margin top acts on the parent container
2022-2028 research and trend analysis report on the global edible essence industry
直方图均衡化
Hands on deep learning (44) -- seq2seq principle and Implementation
2022-2028 global small batch batch batch furnace industry research and trend analysis report
百度研发三面惨遭滑铁卢:面试官一套组合拳让我当场懵逼
回复评论的sql
随机推荐
Golang defer
SQL replying to comments
How to display √ 2 on the command line terminal ̅? This is actually a blog's Unicode test article
Hands on deep learning (36) -- language model and data set
Write a jison parser from scratch (3/10): a good beginning is half the success -- "politics" (Aristotle)
165 webmaster online toolbox website source code / hare online tool system v2.2.7 Chinese version
View CSDN personal resource download details
Are there any principal guaranteed financial products in 2022?
How to batch change file extensions in win10
Advanced technology management - how to design and follow up the performance of students at different levels
Analysis report on the development status and investment planning of China's modular power supply industry Ⓠ 2022 ~ 2028
pcl::fromROSMsg报警告Failed to find match for field ‘intensity‘.
Investment analysis and future production and marketing demand forecast report of China's paper industry Ⓥ 2022 ~ 2028
Hands on deep learning (39) -- gating cycle unit Gru
Go context 基本介绍
Pueue data migration from '0.4.0' to '0.5.0' versions
2022-2028 global industry research and trend analysis report on anterior segment and fundus OTC detectors
Golang type comparison
Global and Chinese market of sampler 2022-2028: Research Report on technology, participants, trends, market size and share
C # use smtpclient The sendasync method fails to send mail, and always returns canceled