通过指向结构体变量的指针变量输出结构体变量中成员的信息。

解题思路:在已有的基础上,本题要解决两个问题:
怎样对结构体变量成员赋值;
怎样通过指向结构体变量的指针访问结构体变量中成员。

#include <stdio.h>
#include <string.h>
struct Student{
 long int num;
 char name[15];
 char sex;
 float score;
};
int main()
{
 struct Student stu,*p;
 p=&stu;//因为stu不是数组所以要加上&符号
 stu.num=10101;
 strcpy(stu.name,"libai");//strcpy函数是将字符串 复制给stu.name
 //使用strcpy函数的时候要声明 #include <string.h>
 stu.sex='f';
 stu.score=99.8;
 printf("学号:%ld\n",stu.num);
 printf("姓名:%s\n",stu.name);
 printf("性别:%c\n",stu.sex);
 printf("分数:%5.1f\n",stu.score); 
 //注意,上面的输出语句可以改成下面的输出语句
 //printf("学号:%ld\n",(*p).num);
 //printf("姓名:%s\n",(*p).name);
 //printf("性别:%c\n",(*p).sex);
 //printf("分数:%5.1f\n",(*p).score); 
 return 0;
} 



结果显示:
学号:10101
姓名:libai
性别:f
分数: 99.8

说明:
为了使用方便和直观,C语言允许把(*p).num用p->num来代替
(*p).name等价于p->name
如果p指向一个结构体变量stu,以下等价:
① stu.成员名(如stu.num)
② (*p).成员名(如(*p).num)
p->成员名(如p->num)

输出信息的所有方法
#include <stdio.h>
struct Student{
  int a;//学号
  char b[20];//姓名
  int c;//成绩   
 } ;//声明结构体类型
int main(){
 struct Student st,*pst;//定义结构体变量,和结构体指针 
struct Student student[3]={
 {201902,"li",78},
 {201904,"chen",92},
 {201909,"zheng",88}
 };
 pst=&st;//指向结构体变量的指针
 st.a=201901;
// (*pst).a=201901; 
// pst->a=201901;//只针对结构体指针引用其成员 ,引用运算符->左侧是结构体指针,右侧是结构体成员 
 / 
 pst=student;//指向结构体数组的指针 
 int i;
 for(i=0;i<3;i++)
  printf("%d %s %d\n",student[i].a,student[i].b,student[i].c);
  //printf("%d %s %d\n",(*(student+i)).a,(*(student+i)).b,(*(student+i)).c);
  //printf("%d %s %d\n",pst[i].a,pst[i].b,pst[i].c);
  //printf("%d %s %d\n",(*(pst+i)).a,(*(pst+i)).b,(*(pst+i)).c);
  //printf("%d %s %d\n",(pst+i)->a,(pst+i)->b,(pst+i)->c);
}


结果显示:
201902 li 78
201904 chen 92
201909 zheng 88
  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱睡觉的小馨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值