【问题标题】:Array - Sort By Modulo array in C数组 - 在 C 中按模数组排序
【发布时间】:2013-09-25 20:26:06
【问题描述】:

大家好,我正在尝试完成我的代码,但我没有获取值,而是获取了值的地址。这是为什么呢?
算法是否构建正确?我需要对用户接收的数组进行排序。余数除以m 等于0 的所有数字将出现在数组的开头,所有余数除以m 等于1 的数字将紧随其后,并带有其余两个数字将在稍后出现,依此类推。将在m 上分配等于m-1 的其余数字。

这是我的输出:

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void SortByModulo(int *arr,int m,int length);
void main()
{   int length,m,i;
    int *arr;
    printf("Please inseret array length:\n");
    scanf("%d" ,&length);
    arr=(int *)malloc(length*sizeof(int));
    if(!arr) // Terms - if there is not enough memory,print error msg and exit the program.
        {
            printf("alloc failed\n");
            return ;
        }
    for(i=0; i<length; i++)
        arr[i]=(int)malloc(length*sizeof(int)); // Allocate memory for each row
    printf("Please inseret %d elemetns :\n",length);
    for (i=0 ; i<length ; i++)
        {
            scanf("%d" , arr[i]);
        }
    printf("Insert a natural number that you want to sort by modulo:\n");
    scanf("%d" ,&m);
    SortByModulo(arr,m,length);
    system("pause");
    return;
}
void SortByModulo(int *arr,int m,int length)
{   int i,j,temp,k;
    for ( i=length ; i>1 ; i--)
    {
        for ( j=0 ; j<i-1 ; j++)
            {
                if((arr[j]%m)>(arr[j+1]%m))
                    {
                      temp=arr[j];
                      arr[j]=arr[j+1];
                      arr[j+1]=temp;
                    }

            }
    }
    for (j=0 ; j<length ; j++)
    {
        printf("%d ", arr[j]);
    }
printf("\n");
}

【问题讨论】:

  • 除非您出于学术原因这样做,否则请使用标准库中的qsort。你只需要传递一个适当的比较函数。

标签: c arrays sorting pointers


【解决方案1】:

首先:你有内存泄漏!并且不需要arr[i]=(int)malloc(length*sizeof(int));。您只需要一个一维数组(arr 的声明是正确的)。删除以下代码:

for(i=0; i<length; i++)
    arr[i]=(int)malloc(length*sizeof(int)); // Allocate memory for each row

注意:不要通过malloc()calloc() 函数转换返回的地址。阅读:Do I cast the result of malloc() and calloc()

scanf 中第二个缺失的&amp;

  scanf("%d", arr[i]);
  //          ^ & missing 

应该是:

  scanf("%d", &arr[i]);

【讨论】:

  • 谢谢你!关于你说的选角? if(!arr)
  • @SagiBinder 我的意思是 arr=(int *)malloc(length*sizeof(int)); 最好写成 arr = malloc(length * sizeof(int)); 。避免强制转换,例如你的类型转换 int*。阅读链接的答案。
猜你喜欢
  • 2011-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多