当前位置:网站首页>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
边栏推荐
- The child container margin top acts on the parent container
- Hands on deep learning (43) -- machine translation and its data construction
- 165 webmaster online toolbox website source code / hare online tool system v2.2.7 Chinese version
- 回复评论的sql
- C language pointer classic interview question - the first bullet
- Four common methods of copying object attributes (summarize the highest efficiency)
- Log cannot be recorded after log4net is deployed to the server
- Global and Chinese market of air fryer 2022-2028: Research Report on technology, participants, trends, market size and share
- ASP. Net to access directory files outside the project website
- Global and Chinese market of wheel hubs 2022-2028: Research Report on technology, participants, trends, market size and share
猜你喜欢
Daughter love: frequency spectrum analysis of a piece of music
Write a mobile date selector component by yourself
What are the advantages of automation?
IIS configure FTP website
El Table Radio select and hide the select all box
How does idea withdraw code from remote push
Histogram equalization
智慧路灯杆水库区安全监测应用
2022-2028 global special starch industry research and trend analysis report
How can people not love the amazing design of XXL job
随机推荐
How web pages interact with applets
Write a jison parser (7/10) from scratch: the iterative development process of the parser generator 'parser generator'
2022-2028 global seeder industry research and trend analysis report
Hands on deep learning (43) -- machine translation and its data construction
Pueue data migration from '0.4.0' to '0.5.0' versions
浅谈Multus CNI
In the case of easyUI DataGrid paging, click the small triangle icon in the header to reorder all the data in the database
Nuxt reports an error: render function or template not defined in component: anonymous
Implementing expired localstorage cache with lazy deletion and scheduled deletion
Intelligent gateway helps improve industrial data acquisition and utilization
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
Rules for using init in golang
C # use smtpclient The sendasync method fails to send mail, and always returns canceled
mmclassification 标注文件生成
PHP book borrowing management system, with complete functions, supports user foreground management and background management, and supports the latest version of PHP 7 x. Database mysql
Go context basic introduction
Fatal error in golang: concurrent map writes
Hands on deep learning (45) -- bundle search
Are there any principal guaranteed financial products in 2022?
2022-2028 global intelligent interactive tablet industry research and trend analysis report