指向结构体变量的指针
//通过结构体变量的指针,输出结构体变量的成员信息
#include <stdio.h>
struct Stu{
int num;
char name[20];
float score;
};
void main()
{
struct Stu stu={1001,"yang",87.5};
struct Stu *p;
p=&stu;
printf("num=%d\nname=%s\nscore=%.2f\n\n",stu.num,stu.name,stu.score);
printf("num=%d\nname=%s\nscore=%.2f\n",(*p).num,p->name,(*p).score);
//(*p)表示的是p指向的是结构体变量,如果不加括号,*p.num就相当于*(p.num)了
//在c语言中,如果p指向一个结构体变量,如上,则有 [stu.num = (*p).num = p->num]
}
输出结果:
num=1001
name=yang
score=87.50
num=1001
name=yang
score=87.50
Press any key to continue
指向结构体数组的指针
//通过结构体变量的指针,输出结构体变量的成员信息
#include <stdio.h>
struct Stu{
int num;
char name[20];
float score;
};
void main()
{
struct Stu stu[3]={{1001,"yang",87.5},{1002,"zhu",98.5},{1003,"zhai",88}};
struct Stu *p;
for(p=stu;p<stu+3;p++)
printf("num=%d\tname=%s\tscore=%.2f\n",p->num,p->name,p->score);
//令p自增做循环,p首先指向stu数组的首地址,然后进行一个自增一个数组长度的运算,循环输出。
}
输出结果:
num=1001 name=yang score=87.50
num=1002 name=zhu score=98.50
num=1003 name=zhai score=88.00
Press any key to continue
用结构体变量和结构体变量的指针做函数参数
//用结构体变量和结构体变量的指针做函数参数
//题目:有n个结构体变量,内含学生学号、姓名以及两门成绩,求输出平均成绩最高的学生信息
//分析:按照模块化思想分析:1.建立一个输入函数输入三个学生 2.比较三个学生平均成绩的大小,并返回最高成绩学生的指针位置 3.打印信息
#include <stdio.h>
struct Stu{
int num;
char name[20];
float score[2];
float ave;
};
void main(){
void input(struct Stu stu[]); //函数声明
struct Stu max(struct Stu stu[]);
void print(struct Stu stud);
struct Stu stu[3],*p=stu; //定义一个实参,p指向这个实参
input(p);
print(max(p)); //当max()返回最高成绩学生地址后,print()函数直接连用输出该学生信息
}
void input(struct Stu stu[]){
int i;
printf("please input the information of students\n");
for(i=0;i<3;i++){
scanf("%d%s%f%s",&stu[i].num,&stu[i].name,&stu[i].score[1],&stu[i].score[2]);//因为有两门课,所以注意输入两个数
stu[i].ave=(stu[i].score[1]+stu[i].score[2])/2;
}
}
struct Stu max(struct Stu stu[]){
int i,m=0;
for(i=0;i<3;i++){ //将最高平均成绩学生固定为第一个学生,和之后的学生进行比较
if(stu[i].ave>stu[m].ave)
m=i;
}
return stu[m]; //返回平均成绩最高的学生
}
void print(struct Stu stud){ //这里打印的是一个学生的全部信息,并且这个信息是由max()返回的
printf("the best student is:\n");
printf("num=%d\tname=%s\tscore1=%.2f\tscore2=%.2f\n",stud.num,stud.name,stud.score[1],stud.score[2]);
}
输出结果:
please input the information of students
1001 li 89 56
1002 zhu 98.5 90.5
1003 yang 90.5 86
the best student is:
num=1002 name=zhu score1=98.50 score2=49.25
Press any key to continue