结构体指针函数综合处理学生成绩
#include <stdio.h>
#include <stdlib.h>
// 结构体,函数以及指针的小综合。
struct Student
{
int score;
char *name; // char name[128];
};
struct Student *initstuScores(int a)
{
int i;
//struct Student stus[3];
//struct Student *p = stus;
struct Student *p = (struct Student *)malloc(a*sizeof(struct Student ));//在堆上面开辟空间,函数结束调用不会释放
for(i=0;i<a;i++){
printf("请输入名字;\n");
p->name = (char *)malloc(128);
scanf("%s",(p->name));
printf("请输入分数;\n");
scanf("%d",&(p->score));
p++;
}
return p - a;
}
void printMes(struct Student *p,int a)
{
int i;
//p = p - a;
for(i=0;i<a;i++){
printf("名字;%s,分数;%d\n",p->name,p->score);
p++;
}
}
struct Student * FindMaxstu(struct Student *p,int a)
{
int i;
struct Student *max;
max = p;
for(i=0;i<a;i++){
if(max->score<p->score){
max = p;
}
p++;
}
return max;
}
struct Student * FindMinstu(struct Student *p,int a)
{
int i;
struct Student *min;
min = p;
for(i=0;i<a;i++){
if(min->score>p->score){
min = p;
}
p++;
}
return min;
}
float getAvaerage(struct Student *p,int a)
{
int i;
int total = 0;
for(i=0;i<a;i++){
total += p->score;
p++;
}
return (float)total/a;
}
int main()
{ int a = 0 ;
printf("请输入总人数;\n");
scanf("%d",&a);
struct Student *pstus = initstuScores(a);
struct Student *max = NULL;
struct Student *min = NULL;
printMes(pstus,a);
min = FindMinstu(pstus,a);
max = FindMaxstu(pstus,a);
printf("max;%s,%d\nmin;%s,%d\nAvaerage;%f\n",max->name,max->score,min->name,min->score,getAvaerage(pstus,a));
/*
int i;
int a ;
printf("请输入总人数;\n");
scanf("%d",&a);
//struct Student stus[3];
//struct Student *p = stus;
struct Student *p = (struct Student *)malloc(a*sizeof(struct Student ));
for(i=0;i<a;i++){
printf("请输入名字;\n");
p->name = (char *)malloc(128);
scanf("%s",(p->name));
printf("请输入分数;\n");
scanf("%d",&(p->score));
p++;
}
p = p - a;
for(i=0;i<a;i++){
printf("名字;%s,分数;%d\n",p->name,p->score);
p++;
}
*/
system("pause");
return 0;
}
需要反复多看!