c - Explain the statement related int *count for the algorithm -
i want make program find repeating integers in array. had 2 methods.
- use nested array. give time complexity of o(n²)
- use auxiliary array find frequency of array.
i have seen solution, limited 1 digit number. uses count array.
int *count = (int *)calloc(sizeof(int), (size - 2));
why (size -2
)?
the code is:
#include<stdio.h> #include<stdlib.h> void printduplicate(int arr[], int size){ int *count = (int *)calloc(sizeof(int),(size-2)); int i; for(i=0;i<size;i++){ if(count[arr[i]] == 1) printf("%d,",arr[i]); else count[arr[i]]++; } } int main(){ int arr[] = {2,5,3,4,2,5,7,8,7}; int size = sizeof(arr)/sizeof(arr[0]); printduplicate(arr,size); return 0; }
actually calloc
statement writen here wrong. here memory allocation is
4*7=28
so here memory allocation 7
integers here can access more 7 elements. wrong in c
language works fine days compilers c
has no array boundary checking may cause write invalid memory.
but how able access memory blocks not allocated?
this answer explained in best way here.
you can see code compiled here.
and when decode algorithm can see that
- for
i=0
arr[0]=2
. , checks whethercount[2]==1
or notcount[2]
represents number of repetitions number2
. first timecount[2]=0
increments value1
- then check
i
values. - when
i=4
checks whethercount[arr[4]]
count[2]==1
or not. if 1 prints it.
Comments
Post a Comment