content
struct declaration
A struct is a collection of heterogeneous elements
struct tag { member-list; }variable-list;
Such as: a person: name + age + gender
struct people { char name[20];//名字 int age; //年龄 char sex[5]; //性别 }pl;//全局变量 int main() { struct people pa;//定义一个局部变量 return 0; }
type of struct member
Members of a structure can be scalars, arrays, pointers, or even other structures.
struct student { int id; char name[10]; }stu; struct school { char add[20]; struct student stu; }sc;
access to structure members
Members of structure variables are accessed through the dot operator (.). The dot operator accepts two operands.
We can see that s has members name and age;
how do we access the members of s, and how do we print them?struct S s; strcpy(s.name, "刘华强");//使用.访问name成员 //对字符串赋值不能用"=",只能用strcpy函数 s.age = 20;//使用.访问age成员
Structure pointer access to members of variables
Sometimes we get not a structure variable, but a pointer to a structure.
How to access members?
structure parameter
Think: Which of the following print1 and print2 functions is better?
struct Stu { int arr[10]; int num; }; struct Stu s = { {1,2,3,4}, 10 }; void print1(struct Stu s)//结构体传参 { printf("%d\n", s.num); } void print2(struct Stu* ps)//结构体地址传参 { printf("%d\n", ps->num); } int main() { print1(s); //传结构体 print2(&s); //传地址 return 0; }
The printf2 function is better!!!
Reason
When passing parameters to a function, the parameters need to be pushed onto the stack.
If a structure object is passed, the structure is too large, and the system overhead of parameter stacking is relatively large, so the performance will be degraded.If you pass a structure pointer in the past, just one address can reduce consumption.
Conclusion:
When passing parameters to a structure, you must pass the address of the structure.