当前位置:网站首页>C language: custom type
C language: custom type
2022-07-27 15:46:00 【FA FA is a silly goose】
One 、 Structure
1. Definition and initialization of structure variables
Go straight to the code :
struct Point {
int x;
int y;
}p1; // Create variables when creating structures , The semicolon must not fall
struct Point p2; // Create variables separately
struct Point p3 = {
1,2 }; // Assign values when creating variables
struct Node {
char str[20];
struct Point p; // Nested structure
}n1 = {
"abcd",{
3,4} };
int main() {
printf("%s\n", n1.str); // Structure access , use . perhaps ->, Variable access is used ., For pointer access ->
printf("%d\n", n1.p.x);
printf("%d\n", n1.p.y);
return 0;
}
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-A5K0M4H1-1632400370757)(C:\Users\10371\AppData\Roaming\Typora\typora-user-images\image-20210923190038919.png)]](/img/87/c7a22d3ef4c70a4171a784b1314910.png)
struct Is the keyword for creating a structure ,Point Is the name of the structure ,p1 It's a structure Point A variable of ,x,y Called structure Point Member variables in , There are two forms of variable creation , First of all , You can create it together when you create a structure , second , Create... Separately , Create rules of type + name , Assignment to structure , You can assign values when creating variables , You can create variables first and then assign values separately . There are two ways to access structures , When accessing with variables , use .( spot ), Then select the attribute corresponding to the variable ; When accessing with pointers , use ->, Then select the corresponding attribute .
2. Structure memory alignment
When we want to calculate the memory size of the structure , You need to know the concept of structure diagram memory alignment , Let's start with two examples :
struct A {
char a;
char b;
int c;
};
struct B {
char a;
int c;
char b;
};
int main(){
printf("%d\n", sizeof(struct A));
printf("%d\n", sizeof(struct B));
return 0;
}
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-u9hpNrap-1632400370761)(C:\Users\10371\AppData\Roaming\Typora\typora-user-images\image-20210923190325486.png)]](/img/0d/bf4fe7bef559ab58796fd1a8ab079f.png)
It turns out that ,A and B The memory size occupied by the two structures is not equal , But its internal member variables are the same , It's just in a different order . The reason for the different results is memory alignment , Let's introduce the rules of structure memory alignment :
The first member is offset from the structure variable by 0 The address of .
Other member variables are aligned to a number ( Align numbers ) An integral multiple of the address of . Align numbers = Compiler default alignment number And The smaller value of the member size . stay VS In the compiler , The default number of alignments is 8.
The total size of the structure is the maximum number of alignments ( Each member variable has an alignment number ) Integer multiple .
If the structure is nested , The nested structure is aligned to an integral multiple of its maximum alignment , The integrity of the structure Body size is the maximum number of alignments ( The number of alignments with nested structures ) Integer multiple .
3. Why memory alignment ?
From the above results, we can probably guess , To save space . in general , There are two main reasons :
Platform reasons :
Some hardware platforms can only get addresses at specific addresses , No memory alignment , There may be errors when taking values .
Performance reasons :
For misalignment , It may take two times to read the data , The following is an example :
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-jchW9qWz-1632400370763)(C:\Users\10371\AppData\Roaming\Typora\typora-user-images\image-20210923192716935.png)]](/img/9f/b7d30e4cdf74c6f4eedc84a59c4f94.png)
In a 32 A platform , In case of misalignment , If you want to read int Of 4 Bytes , For the first time, I will read char One byte of , and int After 3 Bytes ( The small end ), Need to read again , Only then int Of 4 Bytes are completely read ; By comparison , If it is in the case of memory alignment , You only need to read once to put int Of 4 Read it directly .
Two 、 Bit segment
The structure also has the ability to implement bit segments , The problem is coming. , What is a bit segment ?
1. What is a bit segment
The declaration of bit segments and structs are similar , But there are two differences :
- The member of the segment must be int、unsigned int or signed int .
- 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:3;
int _d:4;
};
A It's a bit segment type , Want to know A Size , It can also be used sizeof Come and ask for .
2. Bit segment memory allocation
Take the bit segment above A Come on , Will first open a in memory 4 Byte space , The number after the colon indicates the memory size of the member variable , Unit is bit, The members in the bit segment are allocated from left to right in memory , When a structure contains two bit segments , The second segment is relatively large , Cannot hold the remaining bits of the first bit segment , yes Discard the remaining bits or use , This is uncertain . in general , Compared to the structure , Bit segments can achieve the same effect , But it can save a lot of space , But there are cross platform problems . It's not easy to understand just talking , Let's look at the picture below :
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-ey3DDX7A-1632400370764)(C:\Users\10371\AppData\Roaming\Typora\typora-user-images\image-20210923200518727.png)]](/img/2e/99113e06e38fd51a31aedc27988d14.png)
Of course , Bit segments save more memory than structures , But it has cross platform problems , It needs to be used with caution .
3、 ... and 、 enumeration
1. Definition of enumeration
enum Day// week
{
Mon, // By default Mon The value is 0, The values of the following member variables increase in turn
Tues,
Wed,
Thur,
Fri,
Sat,
Sun
};
Of course, you can also assign values when defining , for example :
enum Color// Color
{
RED=1,
GREEN=2,
BLUE=4
};
2. Advantages of enumeration
We know ,#define You can define constants , Then why use enumeration ?
Advantages of enumeration :
- Increase the readability and maintainability of the code
- and #define The defined identifier comparison enumeration has type checking , More rigorous .
- Easy to use , You can define more than one constant at a time
Since it exists , There is a reason for its existence , Sometimes #define More convenient , Sometimes enumeration is more convenient , We should learn to use reasonably
Four 、 union ( Shared body )
1. Definition of joint type
union Un // Statement
{
char c;
int i;
};
union Un un; // Defining variables
printf("%d\n", sizeof(un)); // Calculate the size of the community
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 at least be able to preserve the largest member ).
union Un
{
int i;
char c;
};
union Un un;
// Is the result of the following output the same ?
printf("%d\n", &(un.i));
printf("%d\n", &(un.c));
// What is the output below ?
un.i = 0x11223344;
un.c = 0x55;
printf("%x\n", un.i);
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-6pp4XA6e-1632400370765)(C:\Users\10371\AppData\Roaming\Typora\typora-user-images\image-20210923202148509.png)]](/img/09/f156123c09f34e4b312c3c478ae5dc.png)
It can be seen from the results ,i and c The address of is the same , Because they share a space , When given separately i、c assignment , After assignment c Will cover before i Part of the value of .
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 .
for example :
union Un1
{
char c[5];
int i;
};
union Un2
{
short c[7];
int i;
};
// What is the output below ?
printf("%d\n", sizeof(union Un1)); //8,c Occupy 5 Bytes , Than i Big , Maximum alignment digit 4, Need to be for 4 Multiple , So for 8
printf("%d\n", sizeof(union Un2)); //16,c Occupy 14 Bytes , The maximum number of alignments is 4, So for 16
边栏推荐
- 【剑指offer】面试题56-Ⅰ:数组中数字出现的次数Ⅰ
- Talk about the index of interview questions
- js寻找数组中的最大和最小值(Math.max()方法)
- Text batch replacement function
- QT (IV) mixed development using code and UI files
- Dan bin Investment Summit: on the importance of asset management!
- 【剑指offer】面试题39:数组中出现次数超过一半的数字
- 传美国政府将向部分美企发放对华为销售许可证!
- Set the position of the prompt box to move with the mouse, and solve the problem of incomplete display of the prompt box
- C语言:三子棋游戏
猜你喜欢
![[0 basic operations research] [super detail] column generation](/img/cd/f2521824c9ef6a50ec2be307c584ca.png)
[0 basic operations research] [super detail] column generation

Half find

Spark troubleshooting finishing

Analysis of spark task scheduling exceptions

直接插入排序

Record record record

C language: function stack frame

Spark 3.0 Adaptive Execution 代码实现及数据倾斜优化

QT (five) meta object properties

Push down of spark filter operator on parquet file
随机推荐
Learn parquet file format
文字批量替换功能
C:浅谈函数
Spark 任务Task调度异常分析
UDP 的报文结构和注意事项
【云享读书会第13期】FFmpeg 查看媒体信息和处理音视频文件的常用方法
JS find the maximum and minimum values in the array (math.max() method)
复杂度分析
C语言:函数栈帧
【剑指offer】面试题45:把数组排成最小的数
Spark TroubleShooting整理
聊聊面试必问的索引
/dev/loop1占用100%问题
Spark 3.0 测试与使用
[Yunxiang book club issue 13] common methods of viewing media information and processing audio and video files in ffmpeg
Is low code the future of development? On low code platform
MLX90640 红外热成像仪测温传感器模块开发笔记(七)
IP protocol of network layer
leetcode-1:两数之和
js操作dom节点