为什么在排序后更改数组元素,C [英] Why are the array elements changed after sort,C

查看:62
本文介绍了为什么在排序后更改数组元素,C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数组的元素发生了变化,并变成了一些永远不会输入的数字。

The elements of the array changed, and became some numbers which are never being input.

#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 
*****************


推荐答案

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

The input you provide is not fitting into int. For example 765654543596 (hex B244912CEC) is exceeding 32 bits, which is probably your int width. If you truncate it to 32 bits you will see exactly the mysterious 1150364908 (hex 44912CEC) you see in the output.

这篇关于为什么在排序后更改数组元素,C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆