C程序设计--结构体--结构体指针

指向结构体变量的指针

//通过结构体变量的指针,输出结构体变量的成员信息
#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
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值