当前位置:网站首页>C language custom type: struct

C language custom type: struct

2022-07-06 08:03:00 Orange cat

Structure

A structure is a collection of values of different types , These values are called member variables , Each member of a structure can be a variable of a different type

Structs are the same as other types of underlying data types , for example int type 、char type
However, the structure can customize the data type to describe complex objects, which will be used in the structure

Structure declaration

The syntactic form of a structure declaration :
Method 1 :

struct book
{
    
   char a[20];
   char b[15];   Member list 
   int c;
};
int main()
{
    
    struct book t;
    
}
  • here struct Is a structure keyword ,book It's the structure label , You can change
  • Inside is the member variable , Different types can be defined
  • Last { } And after :
  • struct book Is the structure type
    t Is a variable created with a structure type

Method 2 :

struct book
{
    
   char name[20];
   char id[15];   Member list 
   int price;
}s1,s2,s3;
  • While creating the structure type , Create variables
  • Method 2 The variables created are Global variables ,
    Method 1 Yes. local variable

Special structure declaration

struct    
{
    
   int a;
   char b;
   float c; 
}s;
  • When declaring a structure , It can be stated incompletely , Similar to incomplete initialization of arrays
    The name of the structure is omitted ( label )
  • This structure declaration is called Anonymous structure type , But only once

Example :
If the members of two anonymous structure types are the same , Is the type the same ?

struct
{
       
   int a;
   char b;
   float c;
}s;
struct
{
       
   int a;
   char b;
   float c;
}*pd;3

int main()
{
    
   *pd = s;
    Whether the two types are equal ?
}
  • Although the above member types are the same
    If you force , There won't be much problem
    But the compiler will think that these are two types , So it's illegal

Structure self reference

  • A structure type can contain another structure type as its member , But it should be used correctly

Here's an example of a mistake

struct G
{
    
   int f;
   struct G;
};
int main()
{
    
  struct G s;
}

This kind of thinking knows that it can't run , Infinite loop , Because if you want to calculate the size of the structure , What's the size

The right way to self reference :

struct Node
 {
      
     struct Node* next;
 };
  • The correct self reference is to include pointers to structures of the same type
  • It is generally used to realize linked list ( It doesn't matter if you don't understand , I didn't learn either )

Whether it can be used Anonymous structure Carry out structure self reference ?

  • The structure type cannot be self referenced through its own variables , Can only be referenced by its own type
  • Because anonymous structures can only be used once

Whether it can be used typedef After renaming the type , Carry out structure self reference ?

typedef struct
{
    
 int data;
 Node* next;
}Node;

Put the anonymous structure , use typedef Rename as Node, Then carry out structure self reference

  • No way , Because to produce Node , You need to have this structure type first , To carry out typedef Type renaming
    It's about whether there are eggs or chickens first

Correct writing :

typedef struct Node
{
    
 int data;
 struct Node* next;
}Node;

Definition and initialization of structure variables

With the above structure type , The next step is to define and initialize

struct K
{
    
	int a;
	char b;
}; 
struct H
{
    
	int a;
	char b;
}pd;  // This is a global variable 
int main()
{
       //  While defining variables , Initial value of Fu 
	struct K b = {
     6,'G'};
	struct H pd = {
     66,'A'};
	printf("%d %c\n", b.a, b.b); // Print 
	printf("%d %c\n", pd.a, pd.b); // Print 

	return 0;
}
  • The first definition is local structural variables , Print after assigning initial value
  • The second definition is the global structure variable , It is also printed after the initial value is assigned

Structure nesting initialization

Nested structure : It refers to the structure contained in the structure

struct KG
{
    
	int a;
	char b;
};
struct H
{
    
	int a;
	char b;
	struct KG q;  //  Nested structure 
};
int main()
{
    
	struct H pd = {
     66,'A',4,'J'};// initialization 

	printf("%d %c %d %c\n", pd.a, pd.b,pd.q.a,pd.q.b); // Print 

	return 0;
}
  • Structure H It contains Structure KG, This is called structural nesting
  • Initialization is the way to find a structure through its members

Structure memory alignment ( Calculate the size of the structure )

Here we discuss how to calculate the size of a structure ?

struct S
{
    
	char a;
	int b;
	char c;
};
int main()
{
    
	struct S pd = {
     0 };
	printf("%d\n", sizeof(s));
	return 0;
}
  • Calculate the variable size normally :6 Bytes
    char a 1 byte
    int b 4 byte
    char c 1 byte

result :
 Insert picture description here
Why did it turn out to be 12 Well ?
If you want to calculate correctly , First, you have to master the alignment rules of the structure :

  • 1 The first member is offset from the structure variable by 0 The address of .
  • 2 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 . VS The default value in is 8
  • 3 The total size of the structure is the maximum number of alignments ( Each member variable has an alignment number ) Integer multiple .
  • 4 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

The illustration :
We calculated previously 6 Why not ?
Instead, the result is 12
 Insert picture description here

 Insert picture description here

Exercise of calculating the size of the structure

Exercises

struct S2
{
    
 char c1;
 char c2;
 int i;
};
printf("%d\n", sizeof(struct S2))

The illustration :
 Insert picture description here

Exercises 1

struct S
{
    
   double c1;
   char c2;
   int i;
};
printf("%d\n",sizeof(struct S));

The illustration :
 Insert picture description here

Exercises 2
The nested calculation method of structure

struct S
{
    
	double c1;
	char c2;
	int i;
};
struct S3
{
    
	char c1;
	struct S s1;
	double d;
};
int main()
{
    
	struct S3 s3 = {
     0 };
	printf("%d\n", sizeof(s3));
	return 0;
}

The illustration :
 Insert picture description here

  • The maximum number of nested structures is not 16
    16 Is the size of the nested members of the structure ,S The maximum number of alignments in is 8
    What to compare is the alignment number , Not the space it takes

Memory alignment always wastes space , Why is there memory alignment ?
There are two reasons :

  1. 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
  2. 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 ; Aligned memory access requires only one access
    ask .
  • To sum up
    Memory alignment of structures is a way of trading space for time

When designing structures , We have to satisfy the alignment , And save space
How to do :

  • Let the members who occupy less space gather together as much as possible .

for example :
S1 and S2 The type of members as like as two peas , however S1 and S2 There are some differences in the amount of space taken up

struct S1
{
    
 char c1;
 int i;
 char c2;
};       s1  Its size is  12  Bytes 
------------------------------------
struct S2
{
    
 char c1;
 char c2;
 int i;
};       s2  Its size is  8  Bytes 

summary :

Tips for calculating the size of structures

  1. Figure out first. The total size of all structure members
  2. find The largest number of structure member sizes
  3. The total size of all structure members Whether it is Structure member size is the largest Multiple of that number
    If not , The result is the next multiple of the largest number

Change the default alignment number

The default alignment number for calculating the size of the structure can be modified
#pragma This preprocessing instruction , We can change our default alignment number

#pragma pack(2)// Set the default alignment number to 2
struct S1
{
    
 char c1;
 int i;
 char c2;
};
#pragma pack()// Unset the default number of alignments , Restore to default 
  • The size of this structure is 8 了
  • If you modify the default alignment number , The maximum alignment number will not exceed the modified alignment number
    The maximum number of alignments above is 2, Not at all 4
#pragma pack(1)// Set the default alignment number to 1
struct S2
{
    
 char c1;
 int i;
 char c2;
};
#pragma pack()// Unset the default number of alignments , Restore to default 
  • The size of this structure is 6
  • Normally, the default alignment number is 2 Several power , It will not be set to an odd number

The significance of this is : When the structure is not aligned properly , I can change the default alignment number myself

offsetof macro Calculate the offset

offsetof It is to calculate the address of a structure member from the beginning (0) What is the deviation of
offsetof The header file for is :《stddef.h》

offsetof Use :

#include<stddef.h>
struct S
{
    
	char c1;
	int i;
	char c2;
};
int main()
{
    
	printf("%d\n", offsetof(struct S, i));
	return 0;
}

result :
Calculated before ,i The offset of is 4
 Insert picture description here

Structural parameters

There are two ways to transfer parameters of structures
1. Shape parameter
Print with . The operator
If it is the way of formal parameters , It is the size of the whole number structure , It takes up a lot of space

struct peo
{
    
	char name[20];
	char srx[10];
	int tele[12];
};
print(struct peo str)
{
    
	printf("%s %s %d\n", str.name, str.srx, str.tele);
}
int main()
{
    
	struct peo s = {
     " Xiao Ming "," male ","15846092751" };
	print1(s);

}

2. Arguments in the form of pointers
Print with -> The operator
In this way, the address is transmitted , The biggest is 4 Or 8 Bytes

struct peo
{
    
	char name[20];
	char srx[10];
	int tele[12];
};
print1(struct peo* str)
{
    
	printf("%s %s %d\n", str->name, str->srx, str->tele);
}
int main()
{
    
	struct peo s = {
     " Xiao Ming "," male ","15846092751" };
	print2(&s);
}
  • If the structure is selected, it is preferred to pass parameters in the form of pointer
    Because if you choose to pass parameters as functions of formal parameters , Parameters need to be stacked .
    If you pass a structure object , The structure is too large , The system overhead of parameter stack pressing is relatively large , So it will lead to performance
    falling .
  • summary :
    When structures transmit parameters , To transfer the address of the structure
原网站

版权声明
本文为[Orange cat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060757394382.html