1

皆さん、コードを完成させようとしていますが、値を取得する代わりに、値のアドレスを取得しています。何故ですか?
アルゴリズムは正しく構築されていますか? ユーザーが並べ替えた配列 Received を配置する必要があります。除算の残りが等しいすべての数値は配列の先頭に表示され、残りの除算が にm等しいすべての数値が続き、残りの 2 つの数値は後で表示されます。 . に等しい分布で残りの数を持続します。 0m1mm-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");
}
4

1 に答える 1

5

最初:メモリリークがあります!そしてarr[i]=(int)malloc(length*sizeof(int));必要ありません。必要な 1 次元配列は 1 つだけです ( の宣言arrは正しいです)。次のコードを削除します。

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

malloc()注: andcalloc()関数によって返されたアドレスをキャストしないでください。read: andの結果をキャストしますか?malloc()calloc()

&scanf の2 番目の行方不明:

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

次のようにする必要があります。

  scanf("%d", &arr[i]);
于 2013-09-20T12:37:21.983 に答える