2010-10-02 132 views
1

我做了一个程序来删除数组中的重复项,但程序的条件总是保持为真。 我明白了问题所在,将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; 
} 
+1

是什么这个意思是:if(*(arr + count)== - 1) - 为什么不使用arr [count] == -1?你的代码乱丢这个... – 2010-10-02 20:17:29

+0

change scanf(“%d”,&arr [i]);对scanf(“%d”,&arr [count]); ; 编辑:btw这是作业,不是吗? – George 2010-10-02 20:18:20

+1

保持数组长度在一个全局变量count中是有问题的。 – Arun 2010-10-02 20:34:17

回答

2

为了除去从阵列重复创建一个方法,即:

  • 各种阵列
  • 计数唯一值
  • 创建一个新的数组,即大小的
  • 开始从应对唯一值1阵列,当它们的值不同时

要在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++; 
+0

我试图搜索数组,找到重复的数据并对其执行删除操作。 – 2010-10-02 20:36:57

+0

@fahad这非常有效!如果你在哪里使用链接列表,这将是一个好主意,但不是与数组。 – Margus 2010-10-02 20:40:27

1

您从未初始化arr。目前它只是一个指针,它没有实际的绑定,所以你可能会覆盖别的东西。

另外,你永远不会递增 scanf(“%d”,& arr [i]); 我想你想读取scanf(“%d”,& arr [counter]);

+0

Thankyou,如果我不知道用户输入多少个数字,我将如何分配内存?我应该分配一些内存并为每次迭代使用realloc增加内存吗? – 2010-10-02 20:23:16