user379888
user379888

Reputation:

Deleting duplicates in the array

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;
}

Upvotes: 1

Views: 817

Answers (2)

Margus
Margus

Reputation: 20038

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++;

Upvotes: 2

Nicholas
Nicholas

Reputation: 7501

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]);

Upvotes: 1

Related Questions