Deep Learning "Custom Type: Structure, Enumeration, Union (C/C++)"

Custom types: structure, enumeration, union

1. Structure
(1) The declaration of the structure

A structure is a collection of values, and these values ​​are called member variables. Each member of the structure can be a variable of a different type.

struct stu//描述一个学生
{
    
    
 char name[20];//名字
 int age;//年龄
 char sex[5];//性别
 char id[20];//学号
}//分号不能丢
(2) Self-reference of the structure

Is it okay to include a member whose type is the structure itself in the structure?

//代码1
struct Node
{
    
    
 int data;
 struct Node next;
};
//可行否?
如果可以,那sizeof(struct Node)是多少?

The correct way to self-reference:

//代码2
struct Node
{
    
    
 int data;
 struct Node* next;
};

note:

//代码3
typedef struct
{
    
    
 int data;
 Node* next; }Node;
//这样写代码,可行否?

//解决方案:
typedef struct Node
{
    
    
 int data;
 struct Node* next; }Node;
(3) Definition and initialization of structure variables
struct Point
{
    
    
 int x;
 int y; }p1; //声明类型的同时定义变量p1
struct Point p2; //定义结构体变量p2
//初始化:定义变量的同时赋初值。
struct Point p3 = {
    
    x, y};
struct Stu        //类型声明
{
    
    
 char name[15];//名字
 int age;      //年龄
};
struct Stu s = {
    
    "zhangsan", 20};//初始化
struct Node
{
    
    
 int data;
 struct Point p;
 struct Node* next; 
}n1 = {
    
    10, {
    
    4,5}, NULL}; //结构体嵌套初始化
struct Node n2 = {
    
    20, {
    
    5, 6}, NULL};//结构体嵌套初始化
(4) Structure memory alignment

Calculate the size of the structure:

//练习1
struct S1
{
    
    
 char c1;
 int i;
 char c2;
};
printf("%d\n", sizeof(struct S1)); //12字节
//练习2
struct S2
{
    
    
 char c1;
 char c2;
 int i;
};
printf("%d\n", sizeof(struct S2));//8字节
//练习3
struct S3
{
    
    
 double d;
 char c;
 int i;
};
printf("%d\n", sizeof(struct S3));//16字节
//练习4-结构体嵌套问题
struct S4
{
    
    
 char c1;
 struct S3 s3;
 double d;
};
printf("%d\n",sizeof(struct S4));//32字节

How to calculate?

  1. The first member is at an address with an offset of 0 from the structure variable.
  2. Other member variables should be aligned to an address that is an integer multiple of a certain number (alignment number).
    Alignment number = the smaller value of the compiler default alignment number and the member size .
    The default value in VS is 8
  3. The total size of the structure is an integer multiple of the maximum alignment number (each member variable has an alignment number).
  4. If the structure is nested, the nested structure is aligned to an integer multiple of its own maximum alignment, and the overall size of the structure is an integer multiple of all maximum alignments (including the alignment of nested structures).

Why is there memory alignment?

1. Platform reason (transplant reason): Not all hardware platforms can access any data at any address; some hardware platforms can only fetch certain types of data at certain addresses, otherwise a hardware exception will be thrown.
2. Performance reasons: Data structures (especially stacks) should be aligned on natural boundaries as much as possible. The reason is that in order to access unaligned memory, the processor needs to make two memory accesses; while aligned memory access only requires one access.

In general:

The memory alignment of the structure is the practice of trading space for time .

When designing the structure, we must not only satisfy the alignment, but also save space, how to do it:

Let the members who occupy a small space gather as much as possible.

(5) Modify the default alignment number
#include <stdio.h>
#pragma pack(8)//设置默认对齐数为8 struct S1
{
    
    
char c1; int i; char c2;
};
#pragma pack()//取消设置的默认对齐数,还原为默认

#pragma pack(1)//设置默认对齐数为8 struct S2
{
    
    
char c1; int i; char c2;
};
#pragma pack()//取消设置的默认对齐数,还原为默认int main()
{
    
    
//输出的结果是什么?
printf("%d\n", sizeof(struct S1)); printf("%d\n", sizeof(struct S2)); return 0;
}

in conclusion:

When the alignment of the structure is inappropriate, we can change the default alignment by ourselves.

(6) Rank

The declaration and structure of bit segments are similar, with two differences:

1. The members of the bit segment must be int, unsigned int or signed int.
2. There is a colon and a number after the member name of the bit segment.

such as:

struct A
{
    
    
int _a:2; 
int _b:5; 
int _c:10; 
int _d:30;
};

Memory allocation

1. The members of the bit segment can be int unsigned \int signed\ int or char (belonging to the integer family) type
2. The space of the bit segment is 4 bytes (int) or 1 byte (char) as needed Way to open up.
3. Bit segments involve many uncertain factors. Bit segments are not cross-platform. Programs that focus on portability should avoid using bit segments.

Cross-platform issues

1. It is uncertain whether the int bit field 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-bit machines have a maximum of 16, 32-bit machines have a maximum of 32, written as 27, there will be problems in 16-bit machines.
3. The members in the bit segment are allocated from left to right in the memory, or the criteria for allocation from right to left have not been defined.
4. When a structure contains two bit segments and the second bit segment has a relatively large member and cannot fit in the remaining bits of the first bit segment, it is uncertain whether to discard the remaining bits or use them.

Application of bit segment
Insert picture description here

Two, enumeration
(1) Definition of enumeration type
enum Day//星期
{
    
    
Mon, Tues, Wed, Thur, Fri, Sat, Sun
};
enum Sex//性别
{
    
    
MALE, FEMALE, SECRET
}enum Color//颜色
{
    
    
RED, GREEN, BLUE
};
(2) Advantages of enumeration

1. Increase the readability and maintainability of the code.
2. Compared with the identifier defined by #define, the enumeration has type checking, which is more rigorous.
3. Prevents naming pollution (encapsulation)
4. Easy to debug
5. Easy to use, multiple constants can be defined at one time

(3) The use of enumeration
enum Color//颜色
{
    
    
RED=1, GREEN=2, BLUE=4
};
enum Color clr = GREEN;//只能拿枚举常量给枚举变量赋值,才不会出现类型的差异。clr = 5;	//ok??
3. Joint (union)
(1) Definition of union type

Union is also a special custom type. Variables defined by this type also contain a series of members. The characteristic is that these members share the same space (so union is also called a union). such as:

//联合类型的声明union Un
{
    
    
char c; int i;
};

//联合变量的定义union Un un;
//计算连个变量的大小printf("%d\n", sizeof(un));
(2) The characteristics of the joint

The members of the union share the same memory space. The size of such a union variable is at least the size of the largest member (because the union must at least be able to store the largest member).

(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 alignment, it must be aligned to an integral multiple of the maximum alignment.

such as:

union Un1
{
    
    
char c[5]; 
int i;
};
union Un2
{
    
    
short c[7]; 
int i;
};
// 下 面 输 出 的 结 果 是 什 么 ? 
printf("%d\n", sizeof(union Un1));//8字节
 printf("%d\n", sizeof(union Un2));//16字节

Guess you like

Origin blog.csdn.net/qq_47364122/article/details/110226123