c - Generic quicksort works fine with int*, but not with void* -


i have generic quicksort function:

void qsort(void* sup,int n,  int(*cmp) (void *x,void *y),   void (*swap) (void *a,void *b)) {  int pv=n/2,l=0,h=n-1;   if(n<2)   return;   while(h-1>=l)  {   if(l==pv)   {    swap(sup+pv,sup+pv+1);    pv++;   }   if(h==pv)   {    swap(sup+pv,sup+(pv-1));    pv--;   }   if(cmp(sup+h, sup+pv))   {    h--;    continue;   }   if(cmp(sup+pv, sup+l))   {    l++;    continue;   }   swap(sup+l,sup+h);   l++,h--;  }  qsort(sup, l, cmp, swap);  qsort(sup+l,n-l, cmp, swap); } 

with these function parameter:

int cmp(int *c1, int *c2) {  return *c1 > *c2; }  void swap(int *a,int *b) {  int c= *a;  *a=*b;  *b=c; } 

the main function following:

int main() {  int arr[4] = {3,4,1,2};  print(arr, 4);  printf("\n\n");  qsort(arr, 4, &cmp, &swap);  print(arr, 4);  return 0; } 

where print is:

void print(int* arr, int size) {  int = 0;  for(; < size; ++i) {   printf("%d \t", arr[i]);  } } 

the problem:

when prototype of qsort is:

void qsort(int* sup,int n,  int(*cmp) (void *x,void *y),   void (*swap) (void *a,void *b)) 

it works great,

but when change sup parameter void*:

void qsort(void* sup,int n,  int(*cmp) (void *x,void *y),   void (*swap) (void *a,void *b)) 

it doesn't work. have idea why?

i'm working code::blocks under windows, mingw.

you must able dereference parameters. void* cannot dereferenced compiler cannot determine type passing. must use explicit casting if pass void*.

this

void qsort(int* sup,int n,  int(*cmp) (void *x,void *y),   void (*swap) (void *a,void *b)) 

is absolutely fine, here

void qsort(void* sup,int n,  int(*cmp) (void *x,void *y),   void (*swap) (void *a,void *b)) 

you passing void* (sup) , 1 cannot dereferenced. first solution fine must either typecast in (*cmp) or define qsort every type.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -