Sag*_*der 1 c arrays sorting pointers
嘿伙计们,我正在尝试完成我的代码,但不是获取值,而是获取值的地址.这是为什么?
算法是否构建正确?我需要安排用户收到的数组排序.所有除以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");
}
Run Code Online (Sandbox Code Playgroud)
第一:你有内存泄漏!而且arr[i]=(int)malloc(length*sizeof(int));不需要.您只需要一个1-D阵列(声明arr是正确的).删除以下代码:
for(i=0; i<length; i++)
arr[i]=(int)malloc(length*sizeof(int)); // Allocate memory for each row
Run Code Online (Sandbox Code Playgroud)
注意:不要通过malloc()和calloc()函数转换返回的地址.阅读:我是否将结果转换为malloc()和calloc()
&scanf中缺少第二个:
scanf("%d", arr[i]);
// ^ & missing
Run Code Online (Sandbox Code Playgroud)
应该:
scanf("%d", &arr[i]);
Run Code Online (Sandbox Code Playgroud)