69,371
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
struct Student
{
int num;
char name[20];
float score;
int age;
};
void main()
{
struct Student a[50];
int temp, sum, num, times;
scanf("%d",&num);
for(temp = 1;temp <= num;temp++)
{
scanf("%d %s %f %d",&a[temp].num,a[temp].name,&a[temp].score,&a[temp].age);
}
for(times = 1;times <= num-1;times++) //冒泡排序
{
for(temp = 1;temp <= num-times;temp++)
{
if(a[temp].score>a[temp+1].score)
{
a[50] = a[temp];
a[temp] = a[temp+1];
a[temp+1] = a[50];
}
}
}
for(temp = 1;temp <= num;temp++)
{
printf("%d %s %g %d\n",a[temp].num,a[temp].name,a[temp].score,a[temp].age);
}
}
#include <stdio.h>
struct Student
{
int num;
char name[20];
float score;
int age;
}a[50];
typedef struct Student
{
int num;
char name[20];
float score;
int age;
}Student;
Student a[50];
struct Student a[50];
那么 a 的范围是 a[0]-a[49];
你排序的时候用a[50]做临时变量导致了越界。
你在声明了 a[50] 后,紧接着的声明:
int temp, sum, num, times;
这样 a[50] 所在的这块内存其实是这几个变量所在的内存区域,排序时由于给 a[50] 做了赋值,导致该内存区域中 temp和time的值改变,并未按照你的意愿在 for 循环中递增。
如果在结构声明后紧接着声明 a[50] ,两处内存就不是连在一起的,程序就正常跑了。
也不能说正常吧,越界总是危险的。