改错题
1. 下列给定程序中,函数proc()的功能是:对M名学生的学习成绩,按从低到高的顺序找出前m(m≤10)名学生来,并将这些学生数据存放在一个动态分配的连续存储区中,将此存储区的首地址作为函数值返回。
请修改程序中的错误,使它能得到正确结果。
注意:不要改动main()函数,不得增行或删行,也不得更改程序的结构。
试题程序:
#include<stdlib.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
#define M 10
typedef struct ss
{
char nun[10];
int s;
}
STU;
STU *proc(STU a[],int m)
{
STU b[M],*t;
int i,j,k;
//****found****
*t=calloc(m,sizeof(STU));
for(i=0; i<M; i++)
b[i]=a[i];
for(k=0; k<m; k++)
{
//****found****
for(i=j=0; i<M; j++)
if(b[i].s<b[j].s)
j=i;
//****found****
t[k].s=b[j].s;
b[j].s=100;
}
return t;
}
void outresuh(STU a[],FILE*pf)
{
int i;
for(i=0; i<M; i++)
fprintf(pf,"No=%s Mark=%d\n",
a[i].num,a[i].s);
fprintf(pf,"\n\n");
}
void main()
{
STU stu[M]={{"A01",77},{"A02",85},{"A03",96},{"A04",65},{"A05",75},{"A06",96},{"A07",76},{”A08",63},{"A09",69},{"A10",78}};
STU*pOrder;
int i,m;
system("CLS");
printf("****THE RESULT****\n");
outresult(stu,stdout);
printf("\nGive the number of the students who have lower score:");
scanf("%d",&m);
while(m>10)
{
printf("\nGive the number of the students who have lower score:");
scanf("%d",&m);
}
pOrder=proc(stu,m);
printf("****THE RESULT****\n");
printf("The low:\n");
for(i=0; i<m; i++)
printf("%s%d\n",pOrder[i].nun,
pOrder[i].s);
free(pOrder);
}
【正确答案】(1)错误:*t=calloc(m,sizeof(STU));
正确:(struct ss*)calloc(m,sizeof(STU));
(2)错误:for(i=j=0; i<M; j++)
正确:for(i=j=0; i<M; i++)
(3)错误:t[k].s=b[j].s;
正确:t[k]=b[j];
【答案解析】 由函数proc()可知,变量t是指向动态存储空间的变量,因此,不能间接访问运算符,而函数calloc()的返回值类型为void *,要进行显式类型转换,因此,“*t=calloc(m,sizeof(STU));”应改为“(struct ss*)calloc(m,sizeof(STU));”。由程序可知,变量i为控制学生个数的变量,因此,“for(i=j=0; i<M; j++)”应改为“for(i=j=0; i<M; i++)”;找出成绩较小的学生记录,直接把整个结构体变量赋给数组b,而不是结构中的某一个成员变量,因此,“t[k].s=b[j].s;”应改为“t[k]=b[j];”。