C 删除数组中的重复项

C 删除数组中的重复项,c,arrays,C,Arrays,我制作了一个程序来删除数组中的重复项,但该程序的if条件始终保持为true。 我了解问题所在,将arr[I]更改为arr[count],并通过malloc分配内存,但程序按原样打印阵列,而不删除重复项 # include<stdio.h> # include<stdlib.h> int count=0; void Delete(int *arr); void Search(int *arr); int main()

我制作了一个程序来删除数组中的重复项,但该程序的if条件始终保持为true。 我了解问题所在,将arr[I]更改为arr[count],并通过malloc分配内存,但程序按原样打印阵列,而不删除重复项

    # include<stdio.h>
    # include<stdlib.h>
    int count=0;
    void Delete(int *arr);
    void Search(int *arr);

    int main()
    {
    int i;
    int *arr;
    arr=(int*)malloc(sizeof(int));
    clrscr();
    printf("Enter array and press -1 to stop:\n");/*stops when -1 occurs*/
    for(count=0;    ;count++)/*count is the count of the numbers*/
    {
        scanf("%d",&arr[count]);
        realloc(arr,sizeof((int)+count));
        fflush(stdin);
        if(*(arr+count)==-1)/*This condition is never true.*/
        break;
    }
    Search(arr);
    for(i=0;i<count;i++)
    {
        printf("%d\t",arr[i]);
    }
    getch();
    return 0;
}

    Search(arr);
    for(i=0;i<count;i++)
    {
        printf("%d",&arr[i]);
    }
    getch();
    return 0;
}
#包括
#包括
整数计数=0;
无效删除(int*arr);
无效搜索(int*arr);
int main()
{
int i;
int*arr;
arr=(int*)malloc(sizeof(int));
clrsc();
printf(“输入数组并按-1停止:\n”);/*在出现-1时停止*/
for(count=0;;count++)/*count是数字的计数*/
{
scanf(“%d”和&arr[count]);
realloc(arr,sizeof((int)+count));
fflush(stdin);
如果(*(arr+count)==-1)/*此条件永远不会为真*/
打破
}
搜索(arr);

对于(i=0;i您从未初始化arr。目前它只是一个指针,没有实际的绑定,因此您可能正在覆盖其他内容

而且,你永远不会递增 scanf(“%d”和&arr[i]);
我想您希望读取scanf(“%d”,&arr[counter]);

从数组中删除重复项,创建一个方法,该方法:

  • 对数组排序
  • 计算唯一值
  • 创建一个大小为唯一值的新数组
  • 当它们的值不同时,开始从一个数组调整到另一个数组
要在c中使用快速排序,您需要比较器函数,如:

int comp(const void *x, const void *y) {
  return (*(int*)x - *(int*)y);
}
然后你可以用以下方式来称呼它:

qsort(array, 10, sizeof(int), comp);
要计算排序数组中的唯一项,请迭代该数组,然后执行以下操作:

if(sortedarray[i]!=sortedarray[i+1]) count++;

这是什么意思:如果(*(arr+count)=-1)-为什么不使用arr[count]=-1?您的代码中充斥着这样的内容…将scanf(“%d”、&arr[i])更改为scanf(“%d”、&arr[count]));编辑:顺便说一句,这是家庭作业,不是吗?将数组长度保留在全局变量中,
count
,是不确定的。虽然问题是C,但查看
unique
的想法可能没有什么害处@Thomas O:这有什么不同吗?谢谢,如果我不知道用户将输入多少个数字,我将如何分配内存?我应该使用a吗为每次迭代分配一些内存并用realloc递增?我试图搜索数组,找到一个副本并对其执行删除。@fahad这非常有效!如果您使用链接列表,这将是一个好主意,但不使用数组。