C language articles - (1) First acquaintance with C language - (12) Structure
structure
Structure is a particularly important knowledge point in C language. Structure makes C language capable of describing complex types.
For example, when describing a student, the student includes: name + age + gender + student number.
Describe a book. This book includes: book title + publisher + directory + author and other information.
These are complex objects, and C language gives the ability to
customize types. One of the custom types is called: structurestruct
Structs are the practice of grouping together some single type
For example, let's now describe a person who has the information of name + age + gender + student number
struct Stu
{
char name[20];//名字
int age; //年龄
char sex[5]; //性别
char id[15]; //学号
};
int main()
{
return 0;
}
We want to build a house, which struct Stu
is our drawing, create a structure object s
, and fill in the data according to the drawing
Initialization of the structure
//打印结构体信息
struct Stu s = {
"张三", 20, "男", "20180101"};
It can be regarded
struct Stu
as a data type, s is created to store data结构体对象
,s
and the data inside is成员名
notstruct Stu
used, and those types inside will not open up space
//.为结构成员访问操作符
printf("name = %s age = %d sex = %s id = %s\n", s.name, s.age, s.sex, s.id);
To print the information in s, it must be printed in the order of types.
"张三", 20, "男", "20180101"
Correspondingly%s,%d,%s,%s
, the order cannot be reversed, and it must be in结构体对象.成员名
the form of
There is also a way to print
//
struct Stu *ps = &s;
printf("name = %s age = %d sex = %s id = %s\n", (*ps).name, (*ps).age, (*ps).sex, (*ps).id);
ps
It is a structure pointer variable, here is the method of the pointer, but it is a bit troublesome, you can use->
the operator directly
struct Stu *ps = &s;
printf("name = %s age = %d sex = %s id = %s\n", ps->name, ps->age, ps->sex, ps-
>id);
ps->name
The meaning isps
to points
to the membername
in, and(*ps).name
the meaning is the same