这是一个按照数学成绩排列学生信息的程序,xcode里面运行时bad access

HE_BANG_BANG 2018-01-20 03:30:42
#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[3];
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;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;
}
...全文
574 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2018-01-22
  • 打赏
  • 举报
回复
“多一少一”问题占程序员常犯错误的10%以上! 避免“多一少一”问题的方法之一是将比如<10甚至<5的数代入程序片断,掰手指头心算验证一下程序到底应该写为 x、x-1、x+1中的哪个? <、<=、==、>、>=中的哪个?
paschen 2018-01-21
  • 打赏
  • 举报
回复
此外student[i + 1]已经越界了,当是为N的时候,i可以为N-1,student[i + 1]则为student[N],越界了,有效索引值只是0~N-1
paschen 2018-01-21
  • 打赏
  • 举报
回复
for (int j = N;j > 0;j++) 这里应该是j--吧
自信男孩 2018-01-20
  • 打赏
  • 举报
回复
#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就会越界。

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧