C语言的一个程序 求找错

来源:百度知道 编辑:UC知道 时间:2024/06/06 19:50:55
#include <stdio.h>
#include <string.h>
#define N 4
void main()
{
char name[N][10]={'\0'};
int t,i,j,score[N]={0};
char nametemp[10];
for(i=0;i<N;i++)
{
puts("please input name and score:");
scanf("%s \n%d",name[i],&score[i]);
}
for(j=0;j<N;j++)
for(i=0;i<N-j;i++)
if(score[i]>score[i+1])
{
t=score[i];
score[i]=score[i+1];
score[i+1]=t;
strcpy(nametemp,name[i]);
strcpy(name[i],name[i+1]);
strcpy(name[i+1],nametemp);
}
for(i=0;i<N;i++);
printf("%s:%d\n",name[i],score[i]);
}
我检查了若干遍,但就是没有发现错误,但就是运行通不过。快来帮我查一下,把我闷死了。

错误是数组越界,另外多写了分号。具体见程序注释。

#include <stdio.h>
#include <string.h>
#define N 4
void main()
{
char name[N][10]={'\0'};
int t,i,j,score[N]={0};
char nametemp[10];
for(i=0;i<N;i++)
{
puts("please input name and score:");
scanf("%s \n%d",name[i],&score[i]);
}
for(j=0;j<N;j++)
for(i=0;i<N-j-1;i++) // i == N-1时,i+1越界,这就是出错的原因,应该减1
if(score[i]>score[i+1])
{
t=score[i];
score[i]=score[i+1];
score[i+1]=t;
strcpy(nametemp,name[i]);
strcpy(name[i],name[i+1]);
strcpy(name[i+1],nametemp);
}
for(i=0;i<N;i++)//; <--- 这个分号多了
printf("%s:%d\n",name[i],score[i]);
}

printf("%s:%d\n",name[i],score[i]); 这里错了!

顶 zotin - 经理 四级
补充2句 for(i=0;i<N;i++);完事后 i==4 而i的值应为0-3
故数组越界