69,369
社区成员
发帖
与我相关
我的任务
分享
#include<string.h>
#include<iostream>
//#include<vector>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
void bubble_sort(struct students student[],int s);
struct students{
char a[32];
int math;
int computer;
};
int main()
{
int N;
printf("Please input the number of the students:\n");
scanf("%d",&N);
struct students *student;
//struct students student[N];
student=(struct students*) malloc(N*sizeof(struct students));
for(int i=0;i<N;i++)
{ printf("Please input the information of the %d th student",i+1);
scanf("%s%d%d",student[i].a,&student[i].math,&student[i].computer);
printf("\n");
}
struct students temp;
for(int j = N;j>0;j--)
for(int i = 0;i < j-1;i++) {
printf("i = %d\n", i);
if(student[i].math > student[i+1].math) //就是这句话bad access
{
temp=student[i];
student[i]=student[i+1];
student[i+1]=temp;
}
}
for(int i=0;i<N;i++)
{
printf("%s %d %d",student[i].a,student[i].math,student[i].computer);
printf("\n");
}
return 0;
}
参考一下吧
出现的原因是因为地址越界;
for(int j=N;j>0;j++)
看一下这个循环,j是从N开始,但是j还是j++;很明显已经越界了。
另外:
for(int i=0;i<j;i++)
这个地方也越界,比如当j=N时, i < j即i < N;那么交换时i+1就会越界。