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