C language structure (STRUCT) and Union (UNION)

xiaoxiao2021-03-06  43

I haven't used my friends to introduce Union. I haven't used this thing before, I don't understand, I will search for some information, and I will also turn it to you. I hope to give it to the jar to correct or supplement. Thank you! Union 1. Joint description and combined variable definitions are also a new data type, which is a special form variable. The joint description and the joint variable definition is very similar to the structure. The form is: UNION Joint Name {data type member name; data type member name; ...} combined variable name; jointly representing a variable public memory location, saving different data types and variables of different lengths at different times . The following example shows a combination A_BC: Union A_BC {INT I; CHAR MM;}; re-uses the combined variables that have been described. For example, a combined variable named LGC is defined as described above, which is written to: UNION A_BC LGC; in the combined variable LGC, an integer I and a character mm utility same memory location. When a combination is explained, the compiler automatically generates a variable, which is the length of the largest variable length in the joint. The method of joint access to its members is the same as the structure. The same combined variable can also define an array or pointer, but when defined as a pointer, use "->" symbol, at which point the joint access member can be expressed as: a joint name-> member name, the joint can appear in the structure It can also be a structure. For example: struct {int Age; char * addr; union {INT i; char * ch;} x;} y [10]; to access the member i in the structural variable Y [1], can be written: y [ 1] .xi; To access the first character of the combined x string pointer CH in the structural variable y [2] can be written: * y [2] .x.ch; if "y [2] .x. * ch; "is wrong. 2. Structure and joint differences and joint differences: 1. Structure and joint consists of multiple different data type members, but at any same time, the joint transfer only holds a selected member, and the structure All members exist. 2. For the assignment of different members, it will be rewritten for other members. The value of the original member does not exist, and the value of different members of the structure does not affect each other. Let's take an example to add an understanding of deep combination.

Example 4: Main () {UNION {/ * Defines a federation * / INT i; struct {/ * defines a structure in the joint * / char number; char second;} Half;} Number; Number.i = 0x4241; / * Joint member assignment * / printf ("% C / N", Number.half.First, Mumber.half.Second); Number.Half.First = 'a'; / * Union structure member assignment * / Number .half.second = 'b'; Printf ("% x / n", number.i); getCh ();} The output result is: AB 6261 From the above example results, it can be seen: When I assigns the value, it is low. Eight bits are the values ​​of first and second; when the first and second assignment characters, the ASCII code of the two characters will also be used as the low eight and high of eight digits of I. In practical problems, a set of data often has different data types. For example, in the student registration form, the name should be a character type; the student number can be integer or a character; the age should be integer; gender should be a character type; the score can be integer or real. It is obvious that this group of data cannot be stored in an array. Because the type and length of each element in the array must be consistent to compile the system processing. In order to solve this problem, another construction data type is given in the C language ---- "Structure". It is equivalent to records in other advanced languages.

"Structure" is a type of constructor, which is composed of several "members". Each member can be a basic data type or another constructive type. The structure is both a "constructed" data type, then defined it before explaining and use, that is, construct it. The function is defined before the function is explained and called the function.

First, the definition of the structure

Define a general form of a structure:

Struct structure name

{

Member list

}

Members are composed of several members, each member is an integral part of the structure. For each member, it must also be described in the form of:

Type indicator member name;

The name of the member name should meet the writing of the identifier. E.g:

Struct stu

{

Int Num;

Char Name [20];

CHAR SEX;

Float score;

}

In this structure definition, the structure is called STU, which consists of four members. The first member is NUM, integer variable; the second member is Name, the character array; the third member is SEX, the character variable; the fourth member is Score, real variable. It should be noted that the semicolon after parentheses is indispensable. After the structure is defined, the variable will be performed. Any variable indicating that the structure STU is composed of the above four members. It can be seen that the structure is a complex data type, which is a collection of number of ordered variables that are fixed and type different.

Second, the structural type variable

The structural variable has the following three methods. The STU defined above is an example.

1. First define the structure and then explain the structural variable. Such as:

Struct stu

{

Int Num;

Char Name [20];

CHAR SEX;

Float score;

}

Struct stu boy1, boy2;

The two variables BOY1 and BOY2 are STU structural types. It is also possible to define a symbol constant to represent a structural type, for example:

#define stu struct stu

STU

{

Int Num;

Char Name [20];

CHAR SEX;

Float score;

}

STU BOY1, BOY2;

2. Describe the structural variables while defining structural types. E.g:

Struct stu

{

Int Num;

Char Name [20];

CHAR SEX;

Float score;

} BOY1, BOY2;

3. Directly explain the structural variables. E.g:

Struct

{

Int Num; char name [20];

CHAR SEX;

Float score;

} BOY1, BOY2;

The third method and the second method are different in the third method, and the structural variable is directly given. The BOY1, BOY2 variables illustrated in three methods have the structure shown in Fig. 7.1. When the BOY1, the BOY2 variable is the STU type, you can assign a value to each member of the two variables. In the above STU structure definition, all members are basic data types or array types. Members can also be a structure that constitutes a nested structure. For example, Figure 7.2 gives another data structure. The following structure definitions are given as shown in Figure 7.2:

Struct date {

Int Month;

Int day;

Int year;

}

Struct {

Int Num;

Char Name [20];

CHAR SEX;

Struct Date Birthday;

Float score;

} BOY1, BOY2;

First, a structure DATE is defined, consists of three members of Month, Day (Japan), Year (year). When the variable BOY1 and BOY2 are defined, the members BIRTHDAY are illustrated as the DATA structure type. Member names can be interfered with each other in the same name in other variables. The representation of structural variable members often use structural variables in the program, often use it as a whole.

In addition to allowing the same type of structural variables to be assigned to each other, including assignment, input, output, calculation, etc., including assignment, input, output, calculation, etc. in addition to the same type of structural variables, including assignment, input, output, calculation, etc.

The general form of structural variable members is: structural variable name. Member name, for example: boy1.num, the first person's school number BOY2.SEX, the second person's gender, if the member itself is a structure, you must find the lowest level Level members can be used. For example: Boy1.birdHday.month, the first month of the first person can be used separately in the program, identical to ordinary variables.

Structural variable assignment

As mentioned earlier, the assignment of structural variables is assigned to each member. The input statement or assignment statement can be used.

[Example 7.1] assigns the structural variable and outputs its value.

[Code: 1: 8D8EE8C82C]

MAIN () {

Struct stu

{

Int Num;

Char * name;

CHAR SEX;

Float score;

} BOY1, BOY2;

Boy1.Num = 102;

Boy1.name = "zhang ping";

Printf ("Input Sex and Score / N);

Scanf ("% C% f", & boy1.sex, & boy1.score;

BOY2 = BOY1;

Printf ("Number =% D / NNAME =% S / N", Boy2.Num, Boy2.Name;

Printf ("SEX =% C / NSCORE =% F / N", Boy2.sex, Boy2.score;

}

[/ code: 1: 8D8EE8C82C]

In this program, use the assignment statement to NUM and NAME two members, and Name is a string pointer variable. Dynamically entered the SEX and Score member values ​​with the Scanf function, and then give BOY2 all members of BOY1. Finally, each member value of BOY2 is output separately. This example shows the assignment, input, and output of structural variables.

Initialization of structural variables

If the structural variable is a global variable or a static variable, it can be initialized to assign values. Initialization assignment cannot be initialized for local or automatic structural variables.

[Example 7.2] External structural variable initialization.

[Code: 1: 8D8EE8C82C]

Struct STU / * Define Structure * /

{

Int Num;

Char * name;

CHAR SEX;

Float score;

} BOY2, BOY1 = {102, "zhang ping", 'm', 78.5};

Main ()

{

BOY2 = BOY1;

Printf ("Number =% D / NNAME =% S / N", Boy2.Num, Boy2.Name); Printf ("SEX =% C / NSCORE =% F / N", Boy2.SEX, Boy2.score;

}

[/ code: 1: 8D8EE8C82C]

In this example, BOY2, BOY1 are defined as external structural variables and the BOY1 is initialized. In the main function, the value of BOY1 is given to BOY2, and then output the value of BOY2 members with two PrintF statements.

[Example 7.3] Static structural variable initialization.

[Code: 1: 8D8EE8C82C]

Main ()

{

Static struct stu / * Define static structural variables * /

{

Int Num;

Char * name;

CHAR SEX;

Float score;

} BOY2, BOY1 = {102, "zhang ping", 'm', 78.5};

BOY2 = BOY1;

Printf ("Number =% D / NNAME =% S / N", Boy2.Num, Boy2.Name;

Printf ("SEX =% C / NSCORE =% F / N", Boy2.sex, Boy2.score;

}

[/ code: 1: 8D8EE8C82C]

In this case, both BOY1 and BOY2 are defined as static partial structural variables, and they can also be assigned to assign.

Architecture

The elements of the array can also be structural types. It can therefore constitute a structural array. Each element of the structural array is a substructure variable having the same structural type. In practical applications, a population having the same data structure is often used in actual applications. Such as a class of student files, a wage watch of a workshop employee.

The definition method of the structural array is similar to the structural variable, simply indicates that it is an array type. E.g:

Struct stu

{

Int Num;

Char * name;

CHAR SEX;

Float score;

} Boy [5];

Define a structure of the architecture BOY1, a total of 5 elements, Boy [0] ~ Boy [4]. Each array element has a structural form of the Struct STU. An array of external structures or static structures can be initialized, for example:

Struct stu

{

Int Num;

Char * name;

CHAR SEX;

Float score;

} Boy [5] = {

{101, "li ping", "m", 45},

{102, "zhang ping", "m", 62.5},

{103, "HE Fang", "F", 92.5},

{104, "Cheng Ling", "F", 87},

{105, "WANG Ming", "M", 58};

}

When the total element is initialized, the array length may not be given.

[Example 7.4] Calculate the average number of students and the number of people who do not have a profit.

[Code: 1: 8D8EE8C82C]

Struct stu

{

Int Num;

Char * name;

CHAR SEX;

Float score;

} Boy [5] = {

{101, "li ping", 'm', 45},

{102, "zhang ping", 'm', 62.5},

{103, "HE Fang", 'F', 92.5},

{104, "Cheng Ling", 'F', 87},

{105, "Wang Ming", 'm', 58},

}

Main ()

{

INT I, C = 0;

FLOAT AVE, S = 0;

For (i = 0; i <5; i )

{

S = Boy [i] .score; if (Boy [i] .score <60) C = 1;

}

Printf ("s =% f / n", s);

AVE = S / 5;

Printf ("Average =% F / Ncount =% D / N", AVE, C);

}

[/ code: 1: 8D8EE8C82C]

An external structure array BOY, a total of 5 elements are defined in this case, and the initialization assignment is made. In the main function, use the for statement to accumulate the SCORE member value of each element in S, such as the value of the score is less than 60 (not grid), that is, the counter C plus 1, the cycle is completed, calculate the average score, and output the total class total points , The average division does not have the number of people.

[Example 7.5] Establishing a classmate address book

[Code: 1: 8D8EE8C82C]

#include "stdio.h"

#define Num 3

Struct MEM

{

Char Name [20];

CHAR Phone [10];

}

Main ()

{

Struct MEM Man [Num];

INT I;

For (i = 0; i

{

Printf ("INPUT NAME: / N");

Gets (Man [i] .name);

Printf ("INPUT Phone: / N");

Gets (Man [i] .phone);

}

Printf ("Name / T / T / TPHONE / N / N");

For (i = 0; i

Printf ("% S / T / T% S / N", Man [i] .Name, Man [i] .phone);

}

[/ code: 1: 8D8EE8C82C]

A structural MEM is defined in this program, which has two members name and phone to indicate names and phone numbers. Define MANs as an array of structures having a MEM type in the main function. In the FOR statement, use the Gets function to enter the value of two members in each element. Then use the PrintF statement in the for statement to output two member values ​​in each element.

Structural pointer variable

Description of the structural pointer variable and use a pointer variable When used to point to a structural variable, it is called a structural pointer variable.

The value in the structural pointer variable is the first address of the structural variable pointed to. This structural variable can be accessed by the structural pointer, which is the same as the case of the array pointer and the function pointer. The general form of structural pointer variable description is:

Struct structure name * structural pointer variable name

For example, the structure of the STU is defined in the previous example 7.1, and if a pointer variable PSTu pointing to the STU is written as:

Struct stu * pstu;

Of course, the PSTU can be specifically described when defining the STU structure. As in the previous type of pointer variables as discussed above, the structural pointer variable must also be assigned before it can be used. Assignment is the first address of the structural variable to the pointer variable and cannot give the structure name to the pointer variable. If BOY is a structural variable that is illustrated as a STU type, then PSTU = & BOY is correct, and: PSTU = & stu is wrong.

Structural names and structural variables are two different concepts and cannot be confused. The structural name can only represent a structure, and the compilation system does not assign memory space to it. The storage space is allocated only when a variable is illustrated as this type of structure. Therefore, the above & stu is wrong, it is impossible to take a structural name of the first address. With a structural pointer variable, you can easily access the various members of the structural variable.

The general form of its access is: (* structural pointer variable). Member name or is:

Structural pointer variable -> member name

For example: (* PSTU) .Num or: pstu-> num

It should be noted that the brackets on both sides are not less, because the membership "." The priority is higher than "*". If you go to the bracket writing * pstu.num is equivalent to * (pstu.num), so that the meaning is completely wrong. The specific description and method of use of structural pointer variables will be described below.

[Example 7.6]

[Code: 1: 8D8EE8C82C]

Struct stu

{

Int Num;

Char * name;

CHAR SEX;

Float score;} boy1 = {102, "zhang ping", 'm', 78.5}, * PSTU

Main ()

{

PSTU = & BOY1;

Printf ("Number =% D / NNAME =% S / N", Boy1.Num, Boy1.Name);

Printf ("SEX =% C / NSCORE =% f / n / n", boy1.sex, boy1.score;

Printf ("Number =% D / NNAME =% S / N", (* PSTU) .Num, (* PSTU) .name;

Printf ("SEX =% C / NSCORE =% F / N / N", (* PSTU). SEX, (* PSTU) .score;

Printf ("Number =% D / NNAME =% S / N", PSTU-> Num, PSTU-> Name);

Printf ("SEX =% C / NSCORE =% F / N / N", PSTU-> SEX, PSTU-> score;

}

[/ code: 1: 8D8EE8C82C]

This example defines a structural STU that defines the STU type structure variable BOY1 and performs initialization assignment, and a pointer variable PSTU that points to the STU type structure is also defined. In the main function, the PSTU is given the address of BOY1, so the PSTU points to BOY1. Then output all members of BOY1 in three forms in the printf statement. As can be seen from the results:

Structural variables. Member name

(* Structural pointer variable). Member name

Structural pointer variable -> member name

These three forms used to represent structural members are completely equivalent. The structural array pointer variable structural pointer variable can point to an array of structures, and the value of the structural pointer variable is the first address of the entire structure array. The structural pointer variable can also point to an element of the structural array, and the value of the structural pointer variable is the first address of the array element of the structure. Set PS to point to the pointer variable of the structure array, the PS also points to the No. 0 element of the array of the structure, PS 1 points to the 1st element, PS i points to the I number. This is consistent with the case of a normal array.

[Example 7.7] An array of structural arrays is output with a pointer variable.

[Code: 1: 8D8EE8C82C]

Struct stu

{

Int Num;

Char * name;

CHAR SEX;

Float score;

} Boy [5] = {

{101, "Zhou Ping", 'M', 45},

{102, "zhang ping", 'm', 62.5},

{103, "liou fang", 'f', 92.5},

{104, "Cheng Ling", 'F', 87},

{105, "Wang Ming", 'm', 58},

}

Main ()

{

Struct stu * ps;

Printf ("NO / TNAME / T / T / TSEX / TSCORE / T / N");

For (PS = Boy; PS

Printf ("% D / T% S / T% C / T% f / t / n", PS-> Num, PS-> Name, PS-> SEX, PS-> score);

}

[/ code: 1: 8D8EE8C82C]

In the program, the external array BOY of the STU structure type is defined and initialized assignment. Define PS in the main function to point to the Stu type. In the expression 1 of the loop statement for, the PS is given the first address of BOY, then loop 5 times, outputs the members in the BOY array. It should be noted that a structural pointer variable can be used to access the structural variable or a member of the structural array element, but cannot point to a member. That is to say, a member is not allowed to give it. Therefore, the following assignments are wrong. PS = & boy [1] .sex; but only: ps = boy; (giving a group head address) or:

PS = & boy [0]; (given the first address of the No. 0 element)

Structural pointer variable function parameters

The structure variable function parameters are allowed in the ANSI C standard. But this transmission is to transmit all members one by one, especially when members are array, which will make the time and space overhead of the transfer, and severely reduce the efficiency of the program. Therefore, the best way is to use pointers, ie, with pointer variables, function parameters. At this time, it is only the address of the first parameter to the address, thereby reducing the cost of time and space.

[Example 7.8] The topic is the same as that of Example 7.4, calculating a number of students average scores and number of people.

Structure pointer variables to program function parameters.

[Code: 1: 8D8EE8C82C]

Struct stu

{

Int Num;

Char * name;

CHAR SEX;

Float score;

} Boy [5] = {

{101, "li ping", 'm', 45},

{102, "zhang ping", 'm', 62.5},

{103, "HE Fang", 'F', 92.5},

{104, "Cheng Ling", 'F', 87},

{105, "Wang Ming", 'm', 58},

}

Main ()

{

Struct stu * ps;

Void AVE (Struct Stu * PS);

PS = BOY;

AVE (PS);

}

Void AVE (Struct Stu * PS)

{

INT C = 0, I;

FLOAT AVE, S = 0;

For (i = 0; i <5; i , ps )

{

S = PS-> score;

IF (PS-> Score <60) C = 1;

}

Printf ("s =% f / n", s);

AVE = S / 5;

Printf ("Average =% F / Ncount =% D / N", AVE, C);

}

[/ code: 1: 8D8EE8C82C]

The function AVE is defined in this program, and its shape is reflected in the structural pointer variable PS. BOY is defined as an external structure array, so it is valid throughout the program. In the main function, the structural pointer variable PS is defined, and the first address of the BOY is given to the PS point to the BOY array. Then use the PS to do the reference function AVE. Complete the calculation average score and statistics in the function AVE and output the result. Compared with the example 7.4, since the programs are all used by the pointer variables, the speed is faster and the program efficiency is higher. .

TOPOIC = Dynamic Storage Assignment

In an array chapter, it has been introduced that the length of the array is predefined, and it is fixed throughout the program. Dynamic array types are not allowed in C language. For example: int N; scanf ("% d", & n); int a [n]; uses variables to represent the length, want to dynamically explain the size of the array, which is wrong. But in actual programming, this often occurs, ie the required memory space depends on the actual input data, and cannot be predetermined. For this problem, it is difficult to solve with an array approach. In order to solve the above problems, the C language provides some memory management functions, which can be dynamically allocated to memory space as needed, or the space that is no longer used, which provides means for efficiently utilizing memory resources. Common memory management functions have the following:

1. Allocate memory space function Malloc

Call form: (Type Design *) Malloc (size) Function: Assign a continuous area with a length "size" byte in the memory area?  姆 刂 刂    虻 刂 刂 刂"Type Desorph" indicates what data types are used to use this area. (Type Design *) Indicates that the return value is forced to convert to the type pointer. "Size" is an unsigned number. For example: PC = (char *) malloc (100); indicates that the memory space allocated, forced to convert to the character array type, the return value of the function is a pointer to the array of characters, and imparts the pointer variable PC . 2. Allocate memory space function Calloc

Calloc is also used to allocate memory space. Call form: (Type Desifter *) Calloc (n, size) function: Allocated the N block length "Size" byte in the memory dynamic storage area?   刂 刂   虻 虻 虻 刂? Type specifier *) for mandatory type conversion. The difference between the Calloc function and the Malloc function is only to allocate an N block area at a time. For example: ps = (struet stu *) Calloc (2, sizeof (struct stu)); SizeOf (Struct Stu) is a structural length of the STU. Therefore, the statement means that the 2-piece continuous zone is assigned according to the length of the STU, and forced to convert to the STU type, and the first address is given to the pointer variable PS.

3. Release the memory space function free

Call form: free (void * ptr); Function: Release a plurality of memory space points to PTR, PTR is an arbitrary type pointer variable, which pointing to the first address of the released area. The released area should be area assigned by the Malloc or Calloc function: [Example 7.9] Assign a zone to enter a student data.

[Code: 1: 8D8EE8C82C]

Main ()

{

Struct stu

{

Int Num;

Char * name;

CHAR SEX;

Float score;

} * Ps;

PS = (struct stu *) Malloc (Struct Stu);

PS-> Num = 102;

PS-> name = "zhang ping";

PS-> sex = 'm';

PS-> score = 62.5;

Printf ("Number =% D / NNAME =% S / N", PS-> Num, PS-> Name);

Printf ("SEX =% C / NSCORE =% F / N", PS-> SEX, PS-> score;

Free (ps);

}

[/ code: 1: 8D8EE8C82C]

In this example, the structure STU is defined to define the STU type pointer variable PS. Then allocate a STU large memory area and assign the first address to the PS to point to the area. Then, the PS is assigned to the pointer variables to each member, and each member value is output with the PrintF. Finally, use the Free function to release the memory space points to the PS. The entire program contains three steps of application for memory space, using memory space, and releases in memory space to realize dynamic allocation of storage space. The concept of the list is a dynamic allocation method in Example 7.9 to allocate memory space for a structure. Each time a piece of space can be used to store a student's data, we can call it a node. How many students should apply for how many memory spaces are applied, that is, how many nodes should be established. Of course, the above work can also be done with the structural arrays, but if you can't accurately grasp the number of students in advance, you will not be able to determine the array size. And when the student is resumed, the space occupied by the element cannot be released from the array. These issues can be solved well with dynamic storage. There is a student to allocate a node, there is no need to predetermine the accuracy of the students, a student's dropout, can delete the node, and release the storage space occupied by this node. Thereby saving valuable memory resources. On the other hand, the method of using an array must take up a continuous memory area. When dynamic allocation, each node can be discontinuous (continuous in the node). The connection between nodes can be implemented with a pointer. That is, a member item is defined in the node structure to store the first address of the next node, which is used to store the address of the address, often referred to as a pointer domain. The first address of the second node can be stored in the first node's pointer domain, and the first address of the third node is stored in the pointer domain of the second node, so that the last node is connected. . The last node is connected due to the subsequent junction, and its pointer domain can be 0. Such a connection method is referred to in the data structure as "linked list". Figure 7.3 is a schematic diagram of a linked list. In Figure 7.3, the 0th junction is called a head junction, which stores the first address of the first node, which has no data, just a pointer variable. Each of the following nodes is divided into two domains, one is a data domain, stores various actual data, such as student Num, Name Name, Gender SEX, and grades SCORE. Another domain is a pointer domain, and the first address of the next node is stored. Each node in the linked list is the same structural type. For example, a node that stores student scholars and grades should be the following structure:

Struct stu

{

Int Num;

int score;

Struct stu * next;

}

The first two members constitute a data field, and the last member NEXT constitutes a pointer domain, which is a pointer variable to the STU type structure. The basic operation of the linked list has the following main operations of the linked list:

1. Establish a linked list;

2. Structure search and output;

3. Insert a node;

4. Delete a node;

These operations are explained below by example.

[Example 7.10] Establish a three node linked list to store students' data. For the sake of simplicity, we assume that only two student data structures are only two people and age.

You can write a function Creat created to create a list. The procedure is as follows:

[Code: 1: 8D8EE8C82C]

#define null 0

#define Type Struct Stu

#define Len Sizeof (Struct Stu)

Struct stu

{

Int Num;

Int agec;

Struct stu * next;

}

TYPE * CREAT (INT N)

{

Struct stu * head, * pf, * pb;

INT I;

For (i = 0; i

{

PB = (Type *) malloc (len);

Printf ("INPUT NUMBER AND AGE / N");

Scanf ("% D% D", & Pb-> Num, & Pb-> AGE);

IF (i == 0)

PF = head = Pb;

ELSE PF-> Next = Pb;

PB-> Next = NULL;

PF = Pb;

}

Return (HEAD);

}

[/ code: 1: 8D8EE8C82C]

The three symbol constants are defined by macro definitions in the function. Here, use Type, Struct Stu, using LEN to indicate the main purpose of SizeOf (Struct Stu) to reduce writing and make reading more convenient in the following procedure. The Structure STU is defined as an external type, and each function in the program can use this definition. The CREAT function is used to create a linked list with n-nodes, which is a pointer function, which is the pointer to the STU structure. The pointer variables of three STU structures are defined in the CREAT function. Head is the head pointer, PF is a pointer variable that pointing the front node of two adjacent points. Pb is the pointer variable of the latter node. In the For statement, the space with the Malloc function is established to equal the length equal to the STU as a node, and the first address gives PB. Then enter the node data. If the current node is the first node (i == 0), the Pb value (this node pointer) is given to the HEAD and PF. If a non-first node, the PB value is given the node member NEXT of the node of the PF. The pointer of PB is the current last node, which refers to the needle domain NULL. The PB value is given to PF to prepare a cycle.

The shape of the CREAT function represents the number of nodes of the built-in table, as the number of cycles of the for statement. Figure 7.4 represents the execution process of the CREAT function.

[Example 7.11] Write a function and find this node in the linked list.

[Code: 1: 8D8EE8C82C]

TYPE * Search (Type * Head, Int N)

{

TYPE * P;

INT I;

P = head;

While (P-> Num! = N && P-> Next! = NULL)

P = p-> next; / * is not the node to find, move one step * /

IF (P-> Num == N) Return (P);

IF (P-> Num! = N && P-> Next == NULL)

Printf ("Node% D Has Not Been Found! / N", N);

}

[/ code: 1: 8D8EE8C82C]

The symbol constants used in this function are the same as the macro of the Example 7.10, equal to STRUCT STU?  辛 鲂鲂? Head is a pointer variable to the linked list, n is the school number to find. Enter the While statement, check if the NUM member of the node is equal to N. If it is not equal to N and the pointer domain is not equal to NULL (not the last node), then moves a node, continue to loop. If this node is found, the node pointer is returned. If the end of the cycle does not find the node, the "Not found" prompt information is output.

[Example 7.12] Write a function and delete the specified node in the list. There are two situations that delete a node:

1. The deleted node is the first node. This situation only needs to point the HEAD to the second node. Head = pb-> next. The process is shown in Figure 7.5.

2. The deleted point is not the first node. This situation can point the front spoint of the deleted point points to the rear node of the deleted point. PF-> Next = Pb-> Next. The process is shown in Figure 7.6.

The function programming is as follows:

[Code: 1: 8D8EE8C82C]

Type * delete (Type * Head, Int Num)

{

TYPE * PF, * PB;

if (Head == NULL) / * is like a holiday, output prompt information * /

{

Printf ("/ Nempty List! / N);

Goto end;

}

PB = HEAD;

While (Pb-> Num! = NUM ​​&& PB-> Next! = NULL)

/ * When not the node to delete, it is not the last node, continue to loop * /

{PF = Pb; PB = PB-> Next;} / * pf points to the current node, PB pointing down the next junction * /

IF (PB-> Num == Num)

{

IF (PB == HEAD)

HEAD = PB-> NEXT;

/ * If you find the deleted point, and the first node, the Head points to the second node, otherwise make the pointer to the node of the PF point to the next junction * /

Else

PF-> Next = Pb-> next;

Free (PB); Printf ("The Node Is Deleted / N);

}

Else

Printf ("The Node Not Been Foud! / N");

End:

Return head;

}

[/ code: 1: 8D8EE8C82C]

There are two ginseng, and Head is a pointer variable to the first node of the linked list, and Num deleted the student number. First determine if the linked list is empty, it is impossible to have an adjjopt point. If it is not empty, the PB pointer points to the first node of the list. After entering the While statement, look up one by one. After finding the deleted node, look at whether it is the first node, if it makes the head point to the second node (ie, delete the first node from the chain), otherwise, the front node of the deleted point is made ( PF refers to the rear node (referred to as the pointer domain) of the deleted node). If the end of the loop does not find the node to delete, the prompt information found "is output. Finally returns the HEAD value.

[Example 7.13] Write a function and insert a node in the specified location in the list. Insert the node in the specified location of a linked list, requiring the list itself must be in a certain regular sequence. For example, in a student data linked list, you are required to insert a node in order. The pointer to which is tied is PI. Can be inserted in three different situations.

1. Original table is a blanket, just make the head point to the tie point. See Figure 7.7 (a)

2. The slot point value is minimized and should be inserted before the first node. In this case, the Head points to the plot point, the pointer domain of the plug point points to the original first node. That is: pi-> next = Pb;

HEAD = Pi; see Figure 7.7 (b)

3. Insert in other locations, see Figure 7.7 (c). In this case, the pointer domain of the front node of the insertion position points points to the tie point, and the pointer domain of the plug point points points to the rear node of the insertion position. That is: pi-> next = pb; pf-> next = pi;

4. Insert in the surface, see Figure 7.7 (d). In this case, the original surface end node pointer domain points to the tie point, and is set to null. which is:

[Code: 1: 8D8EE8C82C]

PB-> Next = Pi;

Pi-> Next = null; type * insert (Type * Head, Type * Pi)

{

TYPE * PF, * PB;

PB = HEAD;

IF (head == null) / * empty table Insert * /

{

HEAD = Pi;

Pi-> next = null;

}

Else

{

While ((pi-> num> pb-> num) && (pb-> next! = null))

{

PF = Pb;

PB = Pb-> next;

} / * Looking for insertion position * /

IF (Pi-> Num <= PB-> NUM)

{

IF (head == PB)

Head = pi; / * Insert * / before the first node

Else

PF-> Next = Pi; / * Insert * /

Pi-> next = Pb;

}

Else

{

PB-> Next = Pi;

Pi-> next = null;

} / * Insert * /

}

Return head;

}

[/ code: 1: 8D8EE8C82C]

This function has two shape parameters for pointer variables, Head points to the linked list, PI pointing to the tie point?  惺 惺 扰 卸 卸 幢 硎 裎 裎 裎 裎  幢 幢 幢... 幢 幢. 幢 幢 幢 幢 幢 幢 幢 幢 幢 幢 幢 幢 幢 幢 幢 幢 幢 幢If you don't have time, use the While statement loop to find the insertion position. After finding it, it is then inserted before the first node is inserted. If the Head point to the slot point is pointed to the original first node, otherwise inserted in other positions, if the inserted node is greater than the table Node, then insert in the end. This function returns a pointer and is the head pointer of the linked list. When the inserted position is before the first node, the inserted new node becomes the first node of the linked list, so the value of the HEAD has changed, so the pointer needs to return this pointer to the main adjustment function.

[Example 7.14] Configure the above, delete nodes, and insert a function organization that is inserted, and then built a function that outputs all nodes, and then calls them with the main function.

[Code: 1: 8D8EE8C82C]

#define null 0

#define Type Struct Stu

#define Len Sizeof (Struct Stu)

Struct stu

{

Int Num;

Int agec;

Struct stu * next;

}

TYPE * CREAT (INT N)

{

Struct stu * head, * pf, * pb;

INT I;

For (i = 0; i

{

PB = (Type *) malloc (len);

Printf ("INPUT NUMBER AND AGE / N");

Scanf ("% D% D", & Pb-> Num, & Pb-> AGE);

IF (i == 0)

PF = head = Pb;

ELSE PF-> Next = Pb;

PB-> Next = NULL;

PF = Pb;

}

Return (HEAD);

}

Type * delete (Type * Head, Int Num)

{

TYPE * PF, * PB;

IF (head == null)

{

Printf ("/ Nempty List! / N);

Goto end;

}

PB = HEAD;

While (Pb-> Num! = NUM ​​&& PB-> Next! = NULL)

{PF = Pb; PB = Pb-> next;}

IF (PB-> Num == Num)

{

IF (PB == HEAD) Head = PB-> NEXT;

ELSE PF-> Next = Pb-> Next;

Printf ("The Node Is Deleted / N);

}

Else

Free (pb);

Printf ("The Node Not Been Found! / N");

End:

Return head;

}

TYPE * INSERT (Type * Head, Type * Pi)

{

TYPE * PB, * PF;

PB = HEAD;

IF (head == null)

{

HEAD = Pi;

Pi-> next = null;

}

Else

{

While ((pi-> num> pb-> num) && (pb-> next! = null))

{PF = Pb;

PB = Pb-> next;}

IF (Pi-> Num <= PB-> NUM)

{

IF (head == pb) Head = Pi;

ELSE PF-> Next = Pi;

Pi-> next = Pb;

}

Else

{

PB-> Next = Pi;

Pi-> next = null;

}

}

Return head;

}

Void Print (Type * HEAD)

{

Printf ("NUMBER / T / TAGE / N");

While (Head! = null)

{

Printf ("% D / T% D / N", Head-> Num, Head-> AGE);

HEAD = head-> next;

}

}

Main ()

{

TYPE * HEAD, * PNUM;

INT N, NUM;

Printf ("INPUT NUMBER OF NODE:");

Scanf ("% d", & n);

HEAD = CREAT (N);

Print (HEAD);

Printf ("INPUT The Deleted Number:"); Scanf ("% D", & NUM);

Head = delete (Head, Num);

Print (HEAD);

Printf ("INPUT the INSERTED NUMBER AND AGE:");

PNUM = (Type *) Malloc (LEN);

Scanf ("% D% D", & pnum-> num, & pnum-> agn);

Head = INSERT (Head, PNUM);

Print (HEAD);

}

[/ code: 1: 8D8EE8C82C]

In this example, the PRINT function is used to output each node data domain value in the linked list. The initial value of the male tail EAD pointed to the first node of the linked list. In the While statement, after outputting the node value, the HEAD value is changed and pointing down the next junction. If the header pointer header header Head should be left, a pointer variable should be set, which gives it to it, and use it to replace HEAD. In the main function, n is the number of established nodes, NUM is a data domain value to be denied; Head is a head pointer to the linked list, and PNum is a pointer to the tie point. The meaning of each line in the main function is:

The sixth line input the number of nodes of the list;

The seventh line adjusts the CREAT function to establish a lin list and return the head pointer to Head;

The eighth line adjustment print function output linked list;

The tenth line enter the students who want to be deleted;

The eleventh line adjusts the delete function to delete a node;

The twelfth line of print function output linked list;

The fourteenth line adjustment Malloc function assigns a node memory space and gives its address to PNUM;

The fifteenth line inputs the data domain value to be inserted into the node;

The sixteenth line adjustment insert function is inserted into the node referred to in PNUM;

Chain Turn again to the Print function output linked list.

From the operation results, first build a linked list of 3 knots, and output its value; then delete 103 nuts, only 105, 108 junction; also enter the 106 number data, insert the node in the rear chain table Take 105, 106, 108. Joint "combination" is also a data structure for constructive types. In a "combination", a variety of different data types can be defined, one of the variables that are described as the "federation" type, allowing any of the data defined by the "United". This is not available in the previous data types. For example, defined a variable that can only be loaded into an integer data, defined as a real value can only be given to real data.

There are many examples in practical problems. For example, in the school's teachers and students, fill in the following form: The "professional" of the name of the name of the age group can be divided into two types "teachers" and "students". A student of "unit" should fill in the class number, and the teachers should fill in a certain department of the department. The class can be expressed as an integer, and the teaching and research room can only use characters. Different types of data are required to fill in the "unit" variable, you must define "unit" as "union" containing two types of integer and character arrays.

"Union" has some similarities between "structure". But both have different inherent. In the structure, each member has its own memory space, the total length of a structural variable is the sum of each member length. In the "United", each member share a memory space, and a combined variable is equal to the longest length in each member. It should be noted that this so-called sharing does not mean that multiple members are simultaneously loaded into a combined variable, but means that the combined variable can be given to any member value, but only one value can be assigned each time. The value is rushed away. As the "unit" variable described earlier, if it is defined as a combination of "class" or "teaching,", it allows the intersection (class) or a string (teaching and research room). Either give an integer value, or give a string, you cannot give it simultaneously. The definition of the federal type and a combined variable describes that a joint type must be defined to explain the variable as the federated type.

First, the union definition

Define a general form of a joint type:

Union United Name

{

Member table

}

The membership table contains several members, and the general form of members is: Naming of the type indicator member name should meet the identifier.

E.g:

Union Perdata

{

Int class;

Char office [10];

}

Define a federated type named PerData, which contains two members, one for integers, member names; another array, the array is named office. After the joint definition, a combined variable description can be performed as a variable of the PerData type, and an integer Class or a character array office can be stored. Second, the joint variable

The description of the combined variables and the structural variables are the same, and there are three forms. That is, first defined, then explain; definitions simultaneously explain and directly explain. Take the PERDATA type as an example, which is as follows:

Union Perdata

{

Int class;

CHAR OFFICAE [10];

}

Union PerData A, B; / * Description A, B is PerData type * /

Or may indicate:

Union Perdata

{

Int class;

Char office [10];

} a, b;

Or directly explain:

union

{

Int class;

Char office [10];

} a, b

The A and B variables after the instructions are Perdata types. Their memory assignment is shown in Figure 7-8. A, the length of the B variable should be equal to the longest length in the member of PerData, ie

The length of the OFFICE array, a total of 10 bytes. As can be seen from the figure, if the B variables are given to the integer value, only two bytes are used, and 10 bytes can be used when applying the character array.

Assignment and use of joint variables

The assignment of the combined variable can only be carried out by a member of the variable. Members of the combined variable are represented as: a combined variable name. Member name, for example, a variable that is illustrated as a PerData type, can use A.CLASS A.Office not allow only combined variable name to assign values ​​or other operations. It is not allowed to assign a value to the joint variable, which can only be carried out in the program? Is it a joint variable that can only give a member value each time a joint variable is the value of a combined variable. A member value of a joint committee.

[Example 7.15] There is a form of teacher and student, and teachers have four names, age, occupations, and teaching and research. The students have four names, age, occupation, and class.

Program input person data, then output it in a table.

[Code: 1: 8D8EE8C82C]

Main ()

{

Struct

{

Char Name [10];

Int agec;

CHAR JOB;

union

{

Int class;

Char office [10];

DEPA;

} body [2];

INT N, I;

For (i = 0; i <2; i )

{

Printf ("INPUT NAME, AGE, JOB and DEPARTMENT / N");

Scanf ("% S% D% C", body [i] .name, & body [i] .age, & body [i] .job);

IF (body [i] .job == 's')

Scanf ("% D", & body [i] .depa.class);

Else

Scanf ("% s", body [i] .depa.office);

}

Printf ("Name / TAGE JOB CLASS / OFFICE / N");

For (i = 0; i <2; i )

{

IF (body [i] .job == 's')

Printf ("% S / T% 3D% 3C% D / N", body [i] .name, body [i] .age, body [i] .job, body [i] .depa.class;

Else

Printf ("% S / T% 3D% 3C% S / N", body [i] .name, body [i] .age, body [i] .job, body [i] .depa.office);

}

}

[/ code: 1: 8D8EE8C82C]

This program uses a structural array body to store personal data, which has four members. The member DEPA is a joint type, which is composed of two members, one for integer Class, one is a character array office. In the first For statement of the program, enter the data of the person, first enter the top three members name, agents of the structure, and then discriminate Job member items, such as "S", the joint DEPA · Class input ( Duty number of the students) Otherwise, the DEPA · Office input (the team name is called to the teacher). Be careful when entering the SCANF statement, any member of the array type, whether it is structural member or a joint member, before the "&" operator can be added before this. Row in line 18

Body [i] .name is an array type, the body [i]. DEPA.Office in line 22 is also an array type, so "&" cannot be added between the two items. The second for statement in the program is used to output the value of each member:

chapter summary

1. Structure and joint is two configuration type data, which is an important means of defining new data types. There are many similarities between structures and joints, which are consisting of members. Members can have different data types. The representation of the member is the same. It can be used in three ways.

2. In the structure, each member has its own memory space, which is existing. The total length of a structural variable is equal to the sum of all members. In the joint, all members cannot occupy its memory space, they cannot exist at the same time. The length of the combined variable is equal to the length of the longest member.

3. "." Is a member operator, which can be used to represent member items, and members can also use the "->" operator.

4. Structure variables can be used as a function parameter, and the function can also return a pointer variable to the structure. The combined variable cannot be used as a function parameter, and the function cannot return to the combined pointer variable. However, you can use a pointer to the federated variable, you can also use the joint array.

5. Structure definitions allow nested, structures, can also be used as members, forming structures, and combined nesters.

6. Link list is an important data structure that facilitates dynamic storage allocation. This chapter describes the one-way linked list, which can also form a two-way linked list, a loop chain list, and the like.

转载请注明原文地址:https://www.9cbs.com/read-74297.html

New Post(0)