【问题标题】:Why are the array elements changed after sort,C为什么排序后数组元素改变了,C
【发布时间】: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

标签: c arrays sorting


【解决方案1】:

您提供的输入不适合int。例如 765654543596 (hex B244912CEC) 超过 32 位,这可能是您的 int 宽度。如果将其截断为 32 位,您将在输出中看到神秘的 1150364908(十六进制 44912CEC)。

【讨论】:

    【解决方案2】:

    您的程序实际上是正确的。除非您输入的内容超过了 int 可以包含的内容。尝试使用不大于 2147483647 的值的程序 &gt;,除非您想将数据类型从 int 更改为可能的 unsigned int。但仍然有两个最大值的限制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-02
      相关资源
      最近更新 更多