【发布时间】:2018-08-25 15:25:29
【问题描述】:
数组的元素发生了变化,变成了一些永远不会被输入的数字。
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 1000
int cmp(int a, int b)
{
return a>b;
}
void sort(int *data, int n, int (*cmp)(int, int))
{
for (;n>1;n--)
{
int i_max = 0;
for(int i = 1;i<n;i++)
if(cmp(data[i],data[i_max])) i_max = i;
int temp = data[i_max];
data[i_max] = data[n-1];
data[n-1] = temp;
}
}
int main()
{
int data[MAX_SIZE] , n;
scanf("%d",&n);
for(int i = 0 ; i < n ; i++)
{
int m;
puts("*****************");
scanf("%d",&m);
for(int j = 0 ; j < m ; j++)
scanf("%d",data+j);
sort(data, m, cmp);
puts("after sorting:");
for(int j = 0 ; j < m ; j++)
{
printf("%d ",data[j]);
}
puts("\n*****************");
}
return 0;
}
输入:
5
5
12
346
5676434535
765654543596
3543456
6
5783945
5293
237894
273894
73
237482
4
27895
719287349723947
1
34
7
3472893
74897598347
757
178
579875498234
129
84
5
420938
23
837485
279
29871
输出:
*****************
after sorting:
12 346 3543456 1150364908 1381467239
(the last two numbers were never input before, and the former number disappeared)
*****************
*****************
after sorting:
73 5293 237482 237894 273894 5783945
*****************
*****************
after sorting:
1 34 27895 586728235
*****************
*****************
after sorting:
84 129 178 757 3472893 54913274 1883154315
*****************
【问题讨论】:
-
你用调试器单步调试了吗?
-
检查您的数组索引是否超出范围。访问索引越界的数组是未定义的行为。
-
这是learn how to debug your programs的最佳时机。
-
@MichaelWalz 索引对我来说很好。
-
排序与它有什么关系?如果没有
sort(),你会得到什么输出?请参阅minimal reproducible example。