填空题
下列给定程序中,函数fun的功能是:对N名学生的学习成绩,按从高到低的顺序找出前m(m≤10)名学生来,并将这些学生的数据存放在一个动态分配的连续存储区中,此存储区的首地址作为函数值返回。
请改正程序中的错误,使它能得出正确的结果。
注意:不要改动main函数,不得增行或删行,也不得更改程序的结构!
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <stdio.h>
#include <malloc.h>
#define N 10
typede* struct ss
{
char num[10];
int s;
}STU;
STU *fun(STU a[], int m)
{
STU b[N], *t;
int i, j, k;
/**********found**********/
*t=calloc(m, sizeof(STU));
for(i=0; i<N; i++)
b[i]=a[i];
for(k=0; k<m; k++)
{
for(i=j=0; i<N; i++)
if(b[i].s>b[j].s)
j=i;
/**********found**********/
t[k].num=b[j].num;
t[k].s=b[j].s;
b[j].s=0;
}
return t;
}
outresult(STU a[], FILE*pf)
{
int i;
for(i=0; i<N; i**)
fprintf(pf, "No=%s Mark=%d/n", a[i].num, a[i].s);
fprintf(pf, "/n/n");
}
void main()
{
STU a[N]={{"A01", 81}, {"A02", 89}, {"A03", 66},{"A04", 87}, {"A05", 77}, {"A06", 90}, {"A07", 79}, {"A08", 61},{"A09", 80}, {"A10", 71}};
STU *pOrder;
int i, m;
system("CLS");
printf("****THE EESULT****/n");
outresult(a, stdout);
printf("/nGive the number of the students who have better score:");
scanf("%d", &m);
while(m>10)
{
printf("/nGive the number of the students who have better score:");
scanf("%d", &m);}
pOrder=fun(a, m);
printf("****THE RESULT****/n");
printf("The top:/n");
for(i=0; i<m; i++)
printf{"%s %d/n", pOrder[i].num, pOrder[i].s);
free(pOrder);
}
【正确答案】
【答案解析】(1)t=calloc(m,sizeof(STU));
(2)t[k]=b[j];
[解析] (1)calloc应用于分配内存空间。调用形式为 (类型说明符*)calloc(n,size),功能:在内存动态存储区中分配n块长度为“size”字节的连续区域,函数的返回值为该区域的首地址,(类型说明符*)用于强制类型转换。calloc函数与malloc 函数的区别在于calloc函数一次可以分配n块区域。例如,ps=(struct stu*) calloc(2,sizeof (struct stu));,其中的sizeof(struct stu)是求stu的结构长度。该语句的意思是:按stu的长度分配两块连续区域,强制转换为stu类型,并把其首地址赋予指针变量ps。在本题中不用考虑那么复杂,根据定义类型STU b[N],*t;就可以看出*t=calloc(m, sizeof(STU))中的错误。
(2)t[k].num=b[j].num的错误旨在考查对结构体概念的掌握和灵活应用程度。