[C] Encyclopedia of structure + custom type knowledge points (basic, advanced, concise, comprehensive)

 Preface: Hello everyone, this is YY ; this blog is mainly about the knowledge points of structures and custom types ; including

  • Basic part: [ Basic knowledge of structure ]
  • Advanced part: [ Custom Type Type ] [ Calculation Structure Memory Size ] [ Bit Segment ] [ Enumeration ] [ Union ]

PS: It is not easy to create, each knowledge point has examples or pictures to help you understand; if it is helpful to you, I hope to get your attention, like, favorite, thank you!  

Table of contents

Structure part: (basic chapter part)

1. Basic knowledge of structure

1. Declaration of structure

* declaration of anonymous struct type 

2. Access structure members

One: normal scene 

Two: When the structure is nested inside the structure  

Three: When the member variable to be modified is a character array (strcpy)

3. Structure parameter passing

4. Definition and initialization of structure

One: Structural renaming (typedef)

Two: the creation of the structure (instantiation)

Three: Initialization of the structure

Custom type section: (advanced section)

1. Custom Type Classification

2. The memory type of the structure

1. Calculate the memory size of the structure - memory alignment

1.: Structure memory alignment rules

Two: Why is there structure memory alignment? 

Three: Considering the memory alignment of the structure, how should the structure members be set?

* Scenario: modify and restore the default alignment 

2. The structure realizes the bit field (filling & portability of the bit field)

1: Definition of bit segment

Two: Memory allocation of bit segments

Three: Uncertainty of bit segments/cross-platform issues

Four: small summary

3. Enumeration (enum)

1. Definition and usage examples of enumerated types

2. Advantages of enumeration over #define 

4. Union

1. The characteristics of the consortium

2. Calculation of the size of the union 

Example 1:

Example 2: 

3. The use of unions (big and small endian)


Structure part: (basic chapter part)


1. Basic knowledge of structure

A structure is a collection of values ​​that become member variables . Each member of the structure can be a variable of a different type.

 Type classification:

  • Built-in types: char, short, int, long, long long (c++ 99 ), float, double, bool (Boolean)
  • Custom types: structure (struct), enumeration (enum), union (union)

1. Declaration of structure

Structure:

  • Struct: Keyword
  • Tag: structure tag
  • Member-list: member list
  • Variable-list: structure variable

example:


* declaration of anonymous struct type 

Features:

  1. You can remove the name of the structure 
  2. Seemingly the same, the compiler treats them as different struct types

 example:


2. Access structure members

There are two access methods:

  • Structure variable . Structure member name (pass value)
  • Structure pointer -> structure member name (address)

One: normal scene 


Two: When the structure is nested inside the structure  


Three: When the member variable to be modified is a character array (strcpy)

strcpy should be used ; reason: the array name is the address of the first element and cannot be overwritten

  


3. Structure parameter passing

There are two types of parameter passing:

  • pass value (pass structure variable )    
  • Passing address (passing structure pointer )

PS: Call by value, the formal parameter is a temporary copy of the actual parameter, and it still takes up space to open up. The call by address only transfers the address, saving space

There are two access methods:

  • Structure variable . Structure member name (pass value)
  • Structure pointer -> structure member name (address)

Value passing scenario:

 

 Addressing scene:

4. Definition and initialization of structure


One: Structural renaming (typedef)

important point:

  • When instantiating, there is no need to write struct Node c again (example: direct Node c)

  • Node cannot be used until renamed

 example:


Two: the creation of the structure (instantiation)

Multiple variables /multiple pointers can be created at the same  time when the structure is declared

example:

struct Book
{  
   char book_name[20];
   char author[20];
   int price;
   char id[15];
}sb3,sb4,*sb5;

等价于struct Book sb3,sb4;

Three: Initialization of the structure

The initialization of the structure is divided into two ways

  • Created directly when declaring
  • Created individually ( created sequentially/not sequentially)

example:

struct Book
{  
   char book_name[20];
   char author[20];
   int price;
   char id[15];
}sb3={"C++","超人",20,"MB666"};//声明时直接创建

strcut Book SB3={"C++","超人",20,"MB666"};//单独创建(按顺序创建)
strcut Book SB3={.price=20};//单独创建(不按顺序创建,直接索引)

不能直接修改成员列表中的数组,要用strcpy!!//详情见同一博客,“访问结构体成员”

Custom type section: (advanced section)


1. Custom Type Classification

Custom type:

  1. Structure (struct)
  2. Enumeration (enum)
  3. union

2. The memory type of the structure

Calculate the memory size of the structure: consider the memory alignment of the structure


1. Calculate the memory size of the structure - memory alignment


1.: Structure memory alignment rules

Alignment: the smaller value of the size of the structure member itself and the default alignment 

PS: The Linux environment does not set the alignment number by default (the alignment number is the size of the structure member itself)

rule:

  1. Each structure member has an alignment number, and the largest alignment number of members is the maximum alignment number of the structure     
  2. The first member of the struct is aligned directly to an offset of 0 relative to the start of the struct variable
  3. Starting from the second member , it must be aligned to an offset that is an integer multiple of a [alignment number]
  4. The total size of the structure must be an integer multiple of the maximum alignment

example:


Two: Why is there structure memory alignment? 

  • Platform reason (porting reason)

  Not all hardware platforms can access arbitrary data at any address; some hardware platforms can only fetch certain types of data at certain addresses, otherwise a hardware exception is thrown.

  • performance reasons

  Data structures (especially stacks) should be aligned on natural boundaries as much as possible.

  The reason is that to access unaligned memory, the processor needs to do two memory accesses ; for aligned memory accesses, only one access is required . That is, sacrifice space in exchange for time .


Three: Considering the memory alignment of the structure, how should the structure members be set?

Try to keep small structure members together

example:

 


* Scenario: modify and restore the default alignment 

  • Set default alignment: pragma pack(1)
  • Restore default to its book: pragma pack( )

example: 


2. The structure implements the bit field  (filling & portability of the bit field)


1: Definition of bit segment

definition:

  • The bits of the bit field refer to the binary bits
  • The numeric part refers to the number of bits required

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

  1. The members of the bit field must be integers such as int, unsigned int , signed int or char
  2. The member name of the bit field must be followed by a colon , and a number
struct A
{
 int _a:2;
 int _b:5;
}

Two: Memory allocation of bit segments

  1. The members of the bit field can be int, unsigned int, signed int or char (integer family);
  2. The space on the bit segment is opened up in the form of 4 bytes (int) or 1 byte (char) as required

        ( Char and int are generally not mixed, the storage direction is not sure, and it may be truncated/integer promoted);

  1. Bit segments involve many uncertain factors. Bit segments are not cross-platform, and programs that focus on portability should avoid using bit segments;

Scenario introduction: Why does the size of A change from 16 to 8 after using the bit segment?

Analysis: struct A, open up space with 4 bytes (int) ;

struct S
{
   int a;
   int b;
   int c;
   int d;
};
printf("%d\n",sizeof(strcut S)); S的大小16

struct A
{
                  先开4byte-32bit空间
   int _a:2;       占掉2个剩下30
   int _b:5;       占掉5个剩下25
   int _c:10;      占掉10个剩下15
   int _d:30;      剩下15个不够占,再开4byte空间
                  总共开了8byte空间
}
printf("%d\n",sizeof(strcut A)); S的大小8


Three: Uncertainty of bit segments/cross-platform issues

  1. Whether the int field is signed int or unsigned int, not sure
  2. The maximum number of bits in the bit segment is uncertain (16-bit machines up to 16, 32-bit machines up to 32; if 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 memory, or from right to left. The standard is not yet determined
  4. When a structure contains two bit fields, the second bit field member is too large to fit in the remaining bits of the first bit field. Whether to choose to discard the remaining bits or reuse them, not sure

Four: small summary

Compared with structures, bit segments can achieve the same effect , but can save space very well , but pay attention to cross-platform issues


3. Enumeration (enum)

 Enumeration, as the name implies: enumerate one by one


1. Definition and usage examples of enumerated types

Use points:

  • Every possible value of the enumeration is a constant
  • The constants of the enumeration have default values ​​(0, 1, 2... in sequence), and the default value is decreased by 1 in sequence
  • These constants can be assigned
  • Partial non-assignment and partial assignment can occur, and the remaining variables after assignment follow the default order and decrease by 1

 Example: Monday to Sunday in a week is limited to 7 days, which can be listed one by one

enum Day 星期
{
  Mon,//默认0
  Tues,//默认1
  Wed,//默认2
  Thur=10,//默认3,赋值成10
  Fri,//按照默认原则,10+1,11
  Sat,//默认12
  Sun//默认13
};
枚举所有可能的取值

2. Advantages of enumeration over #define 

We can define constants with #define, why use enumerations?

Difference: the latter has no type, just a simple replacement (cannot be debugged); the former is an enumeration type;

Advantages of enums:

  • Increase code readability and maintainability
  • Compared with the identifier defined by #define, the enumeration has type checking , which is more rigorous
  • Prevent naming pollution (encapsulation)
  • Easy to debug
  • Easy to use, you can define multiple constants at a time

4. Union


1. The characteristics of the consortium

  • The members of the union share the same memory space , so the size of such a joint variable is at least the size of the largest member (because the union must at least have enough capacity to save the largest member)

PS: calculations involving the size of the union


2. Calculation of the size of the union 

Alignment: the smaller value  of the size of the structure member itself and the default alignment

 Main points:

  • The default alignment number is 8 , take the smaller number of the two as the alignment number
  • 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

Example 1:

analyze:

  • The size of char arr[5] is 1, the default alignment number is 8, take 1 as the alignment number
  • The size of int i is 4, the default alignment number is 8, take 4 as the alignment number
  • The maximum number of alignments for both is 4
  • The maximum member size is 5, which is not an integer multiple of the maximum alignment number 4, so it is aligned to an integer multiple of 8

Example 2: 

PS: The default pair number of short is 2

analyze:

  • The maximum member size is 12, which is an integer multiple of the maximum alignment number 4, so the size of the union is 12

3. The use of unions (big and small endian)

Guess you like

Origin blog.csdn.net/YYDsis/article/details/130455366