C language: Struct's structure array and structure nesting

First, the structure array

Why use an array of structures?

For example, if we define a structure book, obviously each book can be described by a structure of type book. To describe two books requires two such structure variables, and so on, if we are dealing with 10 books, 100 books, 1000 books... Do we need to define each one? We think of the data structure of an array, which can allocate a block of memory at one time to store multiple data, so we can use an array of this structure to store these 1000 (or more) books. We call this form of array an array of structures.

declaration of an array of structures

First, if we define the book structure as follows:

struct book {
	char title[40];
	char author[40];
	float value;
};

Declaring an array of structures is the same as declaring an array of any other type:

struct book library[MAXBKS];//MAXBKS is an int integer

This statement declares library as an array with MAXBKS elements, each element of the array is a structure of type bbook. Therefore, library[0] is a book structure, library[1] is a book structure, and so on.

How to use an array of structures

Use the member operator (".") to represent members in an array of structures:

library //book structure array
library[2] //The element in the array is the third book structure we defined
library[2].title //Array of char type, title member in library[2]
library[2].title[4] //A character in the title member array in library[2]

Second, the nested structure

A structure that contains another structure is called a nested structure.

The nested structure is very useful in many cases, such as building a structure of file information about friends, which must contain the information of the first name (name), and a person's name contains the first and last name. At this time We can represent the name itself as a structure and include it directly when building the friend file structure.

First create a name structure:

struct name{ //name structure declaration
	char firstname[20];
	char lastname[20];
};

With the name structure, the guy structure can be built on this basis:

struct guy{
	struct name handle;//Structure nesting
	char favfood[20];
	char job[20];
	float income;
};

How are nested structures initialized?

The initialization method is the same as the normal structure initialization method:

struct guy fellow = { //Initialize variables
	{"xu","song"},
	"hambergers",
	"student",
	23.00
};

Member operations in nested structures:

fellow.handle.firstname //Run result: xu
fellow.handel.lastname //Run result: song
fellow.favfood //run result: hambergers
fellow.job //Run result: student
fellow.income //Running result: 23.00



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325933599&siteId=291194637