#include <stdio.h>
#include <stdlib.h>
struct Student
{
int chengji;
char* name;
};
struct Student* intstu(int len)
{
int i;
/*struct Student d1[3];
struct Student *p = d1;//此处的*表示标识符申明变量*/
struct Student *p = (struct Student *)malloc(len * sizeof(struct Student));//len表示有len个结构体
//此处在堆上面开辟空间,函数结果的调用不会释放
for (i = 0; i < len; i++)
{
printf("请输入名字:\n");
p->name = (char*)malloc(128);
scanf_s("%s", (p->name));
printf("请输入分数:\n");
scanf_s("%d", &(p->chengji));
p++;//for循环里要指针++;
}
return p-len;//上面补释放要让指针往回走
}
void prinstu(struct Student* p, int len)
{
int i;
for (i = 0; i < len; i++)
{
printf("名字:%s 成绩:%d\n", p->name, p->chengji);
p++;//此处为指针头,要++遍历
}
}
struct Student *findmaxstu(struct Student* p, int len)
{
struct Student* max;
max = p;
int i;
for (i = 0; i < len; i++)
{
if (max->chengji < p->chengji) {
max = p;
}
p++;
}
return max;
}
struct Student *findminstu(struct Student* p, int len)
{
struct Student* min;
min = p;
int i;
for (i = 0; i < len; i++)
{
if (min->chengji > p->chengji) {
min = p;
}
p++;
}
return min;
}
float getaverage(struct Student* p, int len)
{
int i;
int total = 0;
for (i = 0; i < len;i++) {
total += p->chengji;
p++;
}
return (float)total / len;
}
int main()
{
int len = 0;
printf("请输入总人数\n");
scanf_s("%d", &len);
//p = p -len;//此处不能用*p,*表示运算符取地址的意思.指针循环之后往回走到指针头
prinstu(pstus, len);
struct Student* max = NULL;
struct Student* min = NULL;
struct Student* pstus = initstu(len);
prinstu(pstus,len);
max = findmaxstu(pstus, len);
min = findminstu(pstus, len);
printf("max:%s,%d\n,min:%s,%d\n,%d\average=%f\n",max->name,max->chengji, min->name,min->chengji, getaverage);
system("pause");
return 0;
}