[C Language] What is a structure?

What is a structure

A structure is a collection of values ​​called member variables. Each member of the structure can be a variable of different types.

The members of a structure can be scalars, arrays, pointers, or even other structures.

1. Declaration of structure

For example, describe a student:

typedef struct Stu
{
    
    
 char name[20];//名字
 int age;//年龄
 char sex[5];//性别
 char id[20];//学号
}Stu;

2. Definition and initialization of structure variables

struct Point
{
    
    
 int x;
 int y; }p1; //声明类型的同时定义变量p1
struct Point p2; //定义结构体变量p2
//初始化:定义变量的同时赋初值。
struct Point p3 = {
    
    x, y};
struct Stu        //类型声明
{
    
    
 char name[15];//名字
 int age;      //年龄
};
struct Stu s = {
    
    "zhangsan", 20};//初始化
struct Node
{
    
    
 int data;
 struct Point p;
 struct Node* next; 
}n1 = {
    
    10, {
    
    4,5}, NULL}; //结构体嵌套初始化
struct Node n2 = {
    
    20, {
    
    5, 6}, NULL};//结构体嵌套初始化

3. Access to structure members

Accessing Members of Structure Variables Members of structure variables are accessed through the dot operator (.). The dot operator accepts two operands.

For example:

struct Stu s;
strcpy(s.name, "zhangsan");//使用.访问name成员
s.age = 20;//使用.访问age成员

When a structure pointer accesses a member pointing to a variable, sometimes what we get is not a structure variable, but a pointer to a structure. How to access members.

as follows:

struct Stu
{
    
    
 char name[20];
 int age;
};
void print(struct Stu* ps) {
    
    
 printf("name = %s   age = %d\n", (*ps).name, (*ps).age);
    //使用结构体指针访问指向对象的成员
 printf("name = %s   age = %d\n", ps->name, ps->age);
}
int main()
{
    
    
    struct Stu s = {
    
    "zhangsan", 20};
    print(&s);//结构体地址传参
    return 0; }

4. Structure parameter passing

struct S {
    
    
 int data[1000];
 int num;
};
struct S s = {
    
    {
    
    1,2,3,4}, 1000};
//结构体传参
void print1(struct S s) {
    
    
 printf("%d\n", s.num);
}
//结构体地址传参
void print2(struct S* ps) {
    
    
 printf("%d\n", ps->num);
}
int main()
{
    
    
 print1(s);  //传结构体
 print2(&s); //传地址
 return 0; }

Which of the print1 and print2 functions above is better?

The answer is: the print2 function is preferred.

reason:

When a function passes parameters, the parameters need to be pushed onto the stack.

If a structure object is passed and the structure is too large, the system overhead of pushing parameters onto the stack will be relatively large, which will lead to performance degradation.

decline.

in conclusion:

When passing parameters of a structure, the address of the structure must be passed.

Guess you like

Origin blog.csdn.net/Daears/article/details/127424331