tags:

views:

79

answers:

2

I made a program to delete duplicates in an array but the program's if condition always remain true. I understood what the problem was,changed arr[i] to arr[count] and allocated memory via malloc,but the program prints the array as it is without deleting the duplicates.

    # 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  A: 

You never initialized arr. Currently it's just a pointer, it has no actual bound on it, so you could be overwriting something else.

Also, you're never incrementing scanf("%d",&arr[i]); I think you want that to read scanf("%d",&arr[counter]);

Nicholas
Thankyou,how would i allocate memory if I dont know how many numbers will the user enter?Should i allocate some memory and increment it with realloc for each iteration?
fahad
+2  A: 

To remove duplicates from array create a method, that:

  • sorts the array
  • counts unique values
  • creates a new array, that is of size unique values
  • start coping from 1 array to the other, when their values are different

To use quicksort in c, you need comparator function like:

int comp(const void *x, const void *y) {
  return (*(int*)x - *(int*)y);
}

And then you can call it with:

qsort(array, 10, sizeof(int), comp);

To count unique items in sorted array, iterate over the array, and do something like:

if(sortedarray[i]!=sortedarray[i+1]) count++;
Margus
I tried to search the array,find a duplicate and perform deletion on it.
fahad
@fahad That is very in effective! If you where using a linked list that would be a good idea, but not with an array.
Margus