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

  1. for i=0 arr[0]=2. , checks whether count[2]==1 or not count[2] represents number of repetitions number 2. first time count[2]=0 increments value 1
  2. then check i values.
  3. when i=4 checks whether count[arr[4]] count[2]==1 or not. if 1 prints it.

Comments

Popular posts from this blog

angularjs - Redirect to a new template in angular js -

Oracle SQL. How to select specific IDs where value of columns specify criteria? -

Desktop Launcher for Python Script Starts Program in Wrong Path (Linux) -