Punch: 4.23 C Language Chapter - (1) First Know about C Language - (12) Structure

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 Stuis 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 Stuas a data type, s is created to store data 结构体对象, sand the data inside is 成员名not struct Stuused, and those types inside will not open up space

Print

//.为结构成员访问操作符
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);

psIt 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->nameThe meaning is psto point sto the member namein, and (*ps).namethe meaning is the same

Guess you like

Origin blog.csdn.net/iqrmshrt/article/details/124357841