2010-10-02 131 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