当前位置:网站首页>C language - custom type
C language - custom type
2022-04-23 10:22:00 【Xiao Li likes fish】
Catalog
1.1 Structure declaration ( example 1.1)
1.2 Anonymous structure ( example 1.2)
1.3 Structure self reference ( example 1.3)
1.4 typedef Rename type ( example 1.4)
1.5 Structure definition and initialization
1.5.1 Structure definition and initialization ( example 1.5)
1.5.2 Structure nested definition ( example 1.6)
1.6 *** Structure memory alignment
1.6.1 Structure alignment rules
1.6.2 Example of structure alignment (1)
1.6.3 Example of structure alignment (2)
1.6.4 Example of structure alignment (3)
1.6.5 Change the default alignment number
1.6.7 Why is there memory alignment ?
4.2 Consortium size calculation
1. Structure
- Definition : 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 . The combination of different types of variables is the structure .
- Structure declaration : example 1.1
- Anonymous structure : example 1.2
- Structure self reference : example 1.3
- typedef Rename type : example 1.4
- Structure definition and initialization ( Nesting definition ): example 1.5
- *** Structure memory alignment : example 1.6
- Structural parameters : example 1.7
1.1 Structure declaration ( example 1.1)
struct Student // Initial capitalization when naming { char name[20]; // Member variable definition int age; double score; }s1,s2,s3; // Be careful not to miss the semicolon ! |
1.2 Anonymous structure ( example 1.2)
(a) struct |
(b) struct |
Anonymous structures can only be used once !
So there are two structures defined above , Member variables are the same , Can you let p=&x ?
The answer is You can't , Although both are anonymous structures, they do not point to who they are , But in compiler It seems that there are different types of structures , Can't mix .
1.3 Structure self reference ( example 1.3)
struct Node { int data; // Data fields struct Node* next; // Pointer to the domain }; |
int main() { struct Node next; return 0; } |
In the above case, the linked list is simply simulated .
Self reference is Include a member whose type is the structure itself .
1.4 typedef Rename type ( example 1.4)
typedef struct Student //tag Don't omit }Stu; // Rename it to Stu |
int main() { Stu s1; return 0; } |
In the above case struct Student Rename it to Stu.
In the next call to the structure type, you only need to write Stu that will do .
1.5 Structure definition and initialization
1.5.1 Structure definition and initialization ( example 1.5)
struct Student { char name[20]; int age; double score; }s1 = {" Zhang San ",18,95.5}; |
int main() { struct Student s2 = { " Li Si ",19,97.1 }; return 0; } |
The above cases can be seen , You can directly define and initialize the structure object after defining the structure , It can also be in main Define and initialize the structure object in the function .
1.5.2 Structure nested definition ( example 1.6)
Next example 1.5
struct Student struct Person |
int main() struct Person s4 = { " Wang Wu ",20,93.5 }; return 0; |
1.6 *** Structure memory alignment
1.6.1 Structure alignment rules
- Each member variable has an alignment number
- The first variable in the structure is the offset 0 The address of
- Other members should be aligned to the address of an integer multiple of an alignment number
- When there is no default alignment number , Its own size is the alignment number
- The nested structure is aligned to an integral multiple of its maximum alignment
- The total size of the structure is the maximum number of alignments ( The number of alignments with nested structures ) Integer multiple
Align numbers : The compiler's default first alignment number is equal to the size of the member Smaller value
VS The default value in is 8
1.6.2 Example of structure alignment (1)
Suppose the compiler's default alignment number is 4
struct S1
{
char c1; 1,4 -> 1
char c2; 1,4 -> 1
int i; 4
,4 -> 4
};
|
The case on the left shows , c1 The number of alignments for is 1,c2 The number of alignments for is 1,i The number of alignments for is 4. The maximum alignment number of this structure is 4. |
This figure shows the structure stored in memory , Strictly follow the alignment rules of the structure .
Because to meet the sixth point of the alignment rule , Therefore, the total size of the structure is 8 Bytes .
1.6.3 Example of structure alignment (2)
Suppose the compiler's default alignment number is 8
struct S2
{
double d; 8,8 -> 8
char c; 1,8 -> 1
int i; 4,8 -> 4
};
|
The case on the left shows , d The number of alignments for is 8,c The number of alignments for is 1,i The number of alignments for is 4. The maximum alignment number of this structure is 8. |
Because to meet the sixth point of the alignment rule , Therefore, the total size of the structure is 16 Bytes .
1.6.4 Example of structure alignment (3)
Suppose the compiler's default alignment number is 8, Follow example (2)
struct S3
{
char c1; 1,8 -> 1
struct S2 s2; 8,8 -> 8
double d; 8, 8 -> 8
};
|
The case on the left shows , c1 The number of alignments for is 8, s2 The number of alignments for is 1, d The number of alignments for is 4. The maximum alignment number of this structure is 8. |
Pay special attention to the fifth point of the alignment rule , because s2 The maximum number of alignments for is 8, So align to 8 The position of a multiple of . So the size of the whole structure is 32 Bytes .
1.6.5 Change the default alignment number
We know that VS In this environment, the default alignment number is 8, You can use #pragma() To modify the default alignment number
1.6.6 offsetof- macro
- size_t offsetof( structName, memberName );
- Use the header file <stddef.h>
- Its function is to calculate the offset of structure members relative to the starting position ( For example 2 For example ).
#include<stdio.h>
#include<stddef.h>
struct S2
{
double d;
char c;
int i;
};
int main()
{
printf("%u\n", offsetof(struct S2, d));
printf("%u\n", offsetof(struct S2, c));
printf("%u\n", offsetof(struct S2, i));
return 0;
}
1.6.7 Why is there memory alignment ?
- Platform reasons ( Reasons for transplantation ): Not all hardware platforms can access any data on any address ; Some hardware platforms can only take some special data at some addresses Certain types of data , Otherwise, a hardware exception will be thrown .
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 , The processor needs to make two memory accesses ; The aligned memory access only needs one access .
1.7 Structural parameters
#include<stdio.h>
struct S
{
int data[1000];
int num;
};
void print1(struct S s) // Structure object passing parameters
{
printf("%d\n", s.num);
}
void print2(struct S* ps) // Structure address transfer parameter
{
printf("%d\n", ps->num);
}
int main()
{
struct S s = { {1,2,3,4}, 1000 };
print1(s);
print2(&s);
return 0;
}
Next, compare the two print Difference of function :
void print1(struct S s)
{
printf("%d\n", s.num);
}
Structural parameters
|
void print2(struct S* ps)
{
printf("%d\n", ps->num);
}
Structure address transfer parameter
|
When passing parameters to a function, you need to press the stack , It will consume some time and space . If you pass the structure object directly , It will lead to excessive consumption of time and space , Cause performance degradation . therefore , Structural parameters , Pass the address of the structure object !
2. Bit segment
- The declaration of a bit segment is similar to a structure : example 2.1
The member name of the segment is followed by a colon and a number .- The member of the segment must be int、unsigned int or signed int .
- Bit segments are not cross platform .
- VS In the environment , In memory , Low to high storage , Discard the old memory space when it is not enough , Open up new memory space to continue storage .
- Bit segments have a lot of uncertainty :int The bit segment is not clear whether it is signed or unsigned ; The number of maximum digits is uncertain ; It is not clear whether memory is allocated from left to right or from right to left .
2.1 example
#include<stdio.h>
struct S
{
int _a : 2; //_a This member only accounts for 2 individual bit position
int _b : 5;
int _c : 10;
int _d : 30;
};
int main()
{
printf("%d\n", sizeof(struct S));
return 0;
}
alas ! We found that , The above calculated bit segment size is 8 Bytes . The bit segment first applies to the memory 4 Bytes in total 32 A bit , In the _a,_b,_c There are still 15 A bit , But it's not enough _d Store . Apply to memory again 4 Byte store _d, Therefore, the size of this bit segment is 8 Bytes .
3. enumeration
- Definition : keyword enum, List the possible values one by one : example 3.1
- Enumeration advantages : Increase the readability and maintainability of the code ; and #define The defined identifier comparison enumeration has type checking ; It has encapsulation ; Easy to debug ; Easy to use , You can define more than one variable at a time .
3.1( example 1)
enum Color { red, // Undefined default value is 0 green, // Undefined default value is 1 blue // Undefined default value is 2 }; |
3.2( example 2)
enum Color { red, green, blue=4 }; |
enum Color c=4; // FALSE enum Color c=blue; // Correct |
Be careful !: You can only assign enumeration constants to enumeration variables .
4. Consortium ( Shared body )
- Definition : keyword union, Member variables share a memory space , Only one variable can be used at the same time , The size of the consortium is at least the size of the largest member .
- The consortium applies : example 4.1
- Calculation of the size of the consortium : example 4.2
4.1 The consortium applies
Determine whether the current machine is small end storage or large end storage
#include<stdio.h>
int my_check()
{
union U
{
char c;
int i;
}u;
u.i = 1;
return u.c;
}
int main()
{
int ret = my_check();
if (ret == 1)
{
printf(" The small end \n");
}
else
{
printf(" The small end \n");
}
return 0;
}
// The result is : The small end
When you put... In the consortium i Assigned as 1 when , Because the member variables of the consortium share a space , Call again c when , Take out the low address . You can judge whether the machine is big or small .
4.2 Consortium size calculation
The size of the consortium 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 .
#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;
}
// The result is :
//8
//16
union Un1
{
char c[5]; //1 ,8 -> 1
int i; //4 , 8 -> 4
};
|
union Un2
{
short c[7]; //2, 8-> 2
int i; //4 , 8 -> 4
};
|
Un1:char c Opens the 5 Bytes of space .int i It only needs 4 Bytes , Space is enough . But to align to an integer multiple of the maximum number of alignments ,i The number of alignments for is 4, therefore Un1 The size is 8 Bytes .
Un2: Empathy ,Un2 The size is 16 Bytes .
版权声明
本文为[Xiao Li likes fish]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231007339830.html
边栏推荐
- DBA common SQL statements (2) - SGA and PGA
- Shell script interaction free
- 242、有效字母异位词(哈希表)
- Arm debugging (1): two methods to redirect printf to serial port in keil
- 454、四数之和(哈希表)
- 997. Square of ordered array (array)
- C#和数据库连接中类的问题
- 2022 mobile crane driver test question bank simulation test platform operation
- 深度选择器
- Linked list intersection (linked list)
猜你喜欢
JVM——》常用参数
Juc并发编程07——公平锁真的公平吗(源码剖析)
2022茶艺师(初级)考试试题模拟考试平台操作
Jerry's more accurate determination of abnormal address [chapter]
Six practices of Windows operating system security attack and defense
2022年上海市安全员C证考试题库及答案
《Redis设计与实现》
Question bank and answers of Shanghai safety officer C certificate examination in 2022
中职网络安全2022国赛之CVE-2019-0708漏洞利用
Sim Api User Guide(5)
随机推荐
203、移出链表元素(链表)
Read LSTM (long short term memory)
Examination questions and answers of the third batch (main person in charge) of Guangdong safety officer a certificate in 2022
C#和数据库连接中类的问题
Turn: Maugham: reading is a portable refuge
杰理之栈溢出 stackoverflow 怎么办?【篇】
Yarn core parameter configuration
二叉树的构建和遍历
通过流式数据集成实现数据价值(4)-流数据管道
242. Valid Letter ectopic words (hash table)
Windows installs redis and sets the redis service to start automatically
Configuration of LNMP
997、有序数组的平方(数组)
通过流式数据集成实现数据价值(3)- 实时持续数据收集
LeetCode-608. 树节点
2022年制冷与空调设备运行操作考试练习题及模拟考试
206. Reverse linked list (linked list)
349、两个数组的交集
中职网络安全2022国赛之CVE-2019-0708漏洞利用
一文看懂 LSTM(Long Short-Term Memory)