简体   繁体   中英

compare function for anagram program

hey guys i have this code here but i cannot understand what the cmpfunc function does actually i don't understand the return statement can someone explain it to me ? than

#include <stdio.h>
#include <stdlib.h>

int values[] = { 88, 56, 100, 2, 25 };

int cmpfunc (const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}

int main()
{
   int n;

   printf("Before sorting the list is: \n");
   for( n = 0 ; n < 5; n++ ) {
      printf("%d ", values[n]);
   }

   qsort(values, 5, sizeof(int), cmpfunc);

   printf("\nAfter sorting the list is: \n");
   for( n = 0 ; n < 5; n++ ) {
      printf("%d ", values[n]);
   }

  return(0);
}

Start with a qsort description - here it is.

void qsort (void* base, size_t num, size_t size,
            int (*compar)(const void*,const void*));

So you need to write a function with such inputs and output to use in qsort .

int cmpfunc (const void * a, const void * b)

is ok, but inputs are *void and you need to compare integers in your case. So you will need to convert types. That's why there are

 *(int*)a

Finally, return values of cmpfunc must match requirements from qsort description. In article I mentioned at the begging of this post you can find this implementation:

int compareMyType (const void * a, const void * b)
{
  if ( *(MyType*)a <  *(MyType*)b ) return -1;
  if ( *(MyType*)a == *(MyType*)b ) return 0;
  if ( *(MyType*)a >  *(MyType*)b ) return 1;
}   

Your version is just a proper simplification of it.

cmpfnc is comparing the values of of pointers provided. It uses void* so that any kind of data can be passed to it and compared after being converted. First it converts the void* values to int* and then deferences them via * to subtract the integers they are pointing at

When you want to sort an array of some kind you need a comparison function. the comparison function is used by qsort in order to compare two objects in the array. In this case the compare function compares two integers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM