C language | pointer variable to structure variable

Example 40: C language realizes outputting the information in the structure variable through the pointer variable variable pointing to the structure variable.

Problem-solving idea: declare the struct student type in the main function, then define a variable s_1 of struct student type, and define a pointer variable p, which points to an object of struct student type, and set the beginning of the structure variable s_1 Assign the address to the pointer variable p, that is, make p point to s_1, and then assign values ​​to each member of s_1.

Source code demo:

#include<stdio.h>//头文件 
#include<string.h>//为了引用strcpy函数 
int main(){
    
    //主函数 
  struct student{
    
      //学生结构体 
    int num;
    char name[20];
    char sex;
    float score;
  };
  struct student s_1;//定义结构体变量 
  struct student *p;//定义结构体指针变量 
  p=&s_1;//将s_1得地址赋给指针变量 
  s_1.num=10010;//赋值 
  strcpy(s_1.name,"yan");//复制 
  s_1.sex='M';//赋值 
  s_1.score=100;//赋值 
  printf("学号是:%d\n名字是%s\n性别是:%c\n成绩是:%f\n",
  s_1.num,s_1.name,s_1.sex,s_1.score); //输出结果 
  printf("--------------------\n"); //隔开 
  printf("学号是:%d\n名字是%s\n性别是:%c\n成绩是:%f\n",
  (*p).num,(*p).name,(*p).sex,(*p).score); //输出结果 
  return 0;//主函数返回值为0 
}

The compilation and running results are as follows:

学号是:10010
名字是yan
性别是:M
成绩是:100.000000
--------------------
学号是:10010
名字是yan
性别是:M
成绩是:100.000000

--------------------------------
Process exited after 1.116 seconds with return value 0
请按任意键继续. . .

Consider two questions, how to assign values ​​to structure variable members? How to access the members of the structure variable through the pointer to the structure variable?

C language pointer variable pointing to structure variable
More cases can go to the public account: C language entry to proficient

Guess you like

Origin blog.csdn.net/weixin_48669767/article/details/111467000