Reputation:
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
Reputation: 20038
To remove duplicates from array create a method, that:
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
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