The 30th day of learning C [custom type: structure, enumeration, union]

=========================================================================

Relevant code gitee self-collection : C language learning diary: work hard (gitee.com)

 =========================================================================

Continued from the previous issue :

The twenty-ninth day of learning C [Introduction to string functions and memory functions (2)] - Tall Fatty's Blog - CSDN Blog

 =========================================================================

                     

1. Structure

(1). Basic knowledge of structure:

             

A structure is a collection of values ​​called member variables .

Each member of the structure can be a variable of a different type .

                     


                    

(2). Declaration of structure:

                

struct tag         

{                        

                member - list;

}variable - lest;

                 

                  

struct   --  structure label

tag  --  custom structure name

 member-list   --  list of members

variable - lest   --  structure variable list

                     

Example:

                     


                    

(3). Special statement:

              

Anonymous structure : When declaring a structure , it can be declared incompletely , that is, the structure tag (tag) is omitted when declaring

                     

Example:

                     


                    

(4). Self-reference of structure:

           

Include a member in a struct of type the struct itself (like recursion?)

                

Example:

                     


                    

(5). Definition and initialization of structure variables:

                

Two examples of definitions:

                 

Two initialization instances:

                 

A struct member list contains another struct instance:

                     


                    

(6). Structure memory alignment (emphasis):

              

Used to calculate the size of the structure

           

           

Alignment rules for structures:

          

1. The first member is at the address whose offset from the structure variable is 0 .

                      

2. Other member variables should be aligned to an address that is an integer multiple of a certain number (alignment number) .

  • Alignment = the smaller value  between the default alignment of the compiler and the size of the member .
  • The default value in VS is 8. There is no default alignment number in Linux . The alignment number is the size of the member itself

                     

3. The total size of the structure is an integer multiple of the maximum alignment number ( each member variable has an alignment number ) .

Example:

                   

4. If a structure is nested , the nested structure is aligned to an integer multiple of its maximum alignment number , and the overall size of the structure is equal to the maximum alignment number ( including the alignment number of the nested structure ) Integer multiples .

Example:

           

           

Reasons for needing 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 is 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 ;

Whereas aligned memory access requires only one access .

           

           

In general:

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

When designing the structure , we must not only satisfy the alignment , but also save space ;

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

                     


                    

(7). Modify the default alignment number:

                

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

Use the #pragma preprocessing directive to modify the default alignment

Example:

                 


                    

(8). Structure parameter passing:

               

When a function passes parameters , the parameters need to be pushed onto the stack, which will cause system overhead in time and space .

If when passing a structure object , the structure is too large ,

The system overhead of parameter pushing is relatively large , which will lead to a decrease in performance .

Therefore, when the structure is passed as a parameter , it is best to pass the address of the structure .

Example:

            

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

             

2. Bit field (bit field)

(1). What is a bit segment:

              

The declaration of a bit field is similar to that of a structure,

There are two differences:

1. The members of the bit field must be int , unsigned int or signed int .

2. There is a colon and a number after the member name of the bit segment .

            

This number refers to the binary digits occupied by this member variable ,

Limit the space of the member variable to save memory .

             

The size of the bit field is the number of bytes required after adding all the "numbers" ,

If there are not enough bytes to store , add a unit of bytes .

Example:

                     


                    

(2). Memory allocation of bit segment:

                 

  • The members of the bit field can be int , unsigned int , signed int or char (belonging to the integer family ) type
  • The space of the bit field is opened up in the form of 4 bytes ( int ) or 1 byte ( char ) according to the need .
  • Bit segments involve many uncertain factors , bit segments are not cross-platform , and programs that focus on portability should avoid using bit segments .

                     

Example:

                     


                    

(3). The cross-platform problem of bit segment:

             

1. Whether an int bit field is treated as a signed number or an unsigned number is undefined .

             

2. The maximum number of bits in a bit field cannot be determined .

( Maximum 16 for 16-bit machines , maximum 32 for 32-bit machines , if written as 27 , there will be problems on 16-bit machines .)

             

3. Whether the members in the bit segment are allocated from left to right in memory or from right to left has not yet been defined .

             

4. When a structure contains two bit segments , and the second bit segment is too large to accommodate the remaining bits of the first bit segment , it is uncertain whether to discard the remaining bits or use them .

             

Summarize:

Compared with the structure , the bit segment can achieve the same effect , and can save space very well ,

But there are cross-platform issues .

                     


                    

(4). The use of bit segments:

              

In the implementation of the underlying network ,

The structure when packing the data is packed in the form of bit segments .

           

( The format of the ip packet :)

            

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

             

3. Enumeration

Enumeration, as the name suggests, enumerates one by one

List the possible values ​​and list them one by one

           

For example in our real life:

There are only 7 days in a week from Monday to Sunday , which can be listed one by one

Gender: male, female, confidential , you can also list them one by one

There are 12 months in the month, and you can also list them one by one

           

This is where enumerations can be used .

           

(1). Definition of enumeration type:

            

The enum Color defined in the following example is an enumeration type .

The content in {} is the possible value of the enumeration type , also called enumeration constant .

These possible values ​​are all valid , starting from 0 by default and increasing by 1 in turn ,

Of course, the initial value can also be assigned when declaring the enumeration type .

              

Example:

                     


                    

(2). Advantages of enumeration:

               

We can use #define to define constants , why use enums ?

          

Advantages of enums:

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. Only enumeration constants can be used to assign values ​​to enumeration variables , and there will be no type difference

3. Easy to debug

4. Easy to use , you can define multiple constants at a time

            

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

             

4. Union (community)

(1). Definition of union type:

        

Unions are 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 the union is also called the community ).

                     


                    

(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 preserve the largest member .

              

Example:

(Because the union members all share the same space , only one union member can be used at the same time )

                     


                    

(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 integer multiple of the maximum alignment ,

It must be aligned to an integer multiple of the maximum alignment number .

              

Example:

Guess you like

Origin blog.csdn.net/weixin_63176266/article/details/131881119