-1

This has been confusing me for sometime, not sure if someone can understand what I am trying to drive at

Source: https://www.oreilly.com/library/view/algorithms-in-a/9780596516246/ch04s06.html

I am trying to figure out what exactly does passing cmp as the argument into buildHeap does

buildHeap (ar, cmp, n);

the book appears to describe cmp as the comparator function (How does the compare function in qsort work?) and given that

static void buildHeap (void **ar, int(*cmp)(const void *,const void *), int n) {

Am i right to say that

int(*cmp)(const void *,const void *)

is essentially the C equivalent to a delegate in c#?

i.e. passing cmp into buildHeap teaches buildHeap on what function to implement, being the comparator function (which fits the signature of:)

int(*cmp)(const void *,const void *)

Would there be another way for me to teach buildHeap to do a comparator function without passing cmp?

  • Possible duplicate of [How do function pointers in C work?](https://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work) – Osiris Jan 30 '19 at 13:04
  • Thank you, the bulk of the question was answered there. Other than the final question I think? – youcantcme Jan 30 '19 at 13:10
  • Yes, this is same as C# delegate. Func<> in this case. This comparator function returns int as result and takes two const void * pointers as parameters. – Rez Trentnor Jan 30 '19 at 13:11
  • For the last question, passing the function is maybe the best option. You could also pass an `int` or `char *` and parse it to know the type and then compare them proper. – Osiris Jan 30 '19 at 13:12
  • Thanks guys. very swift help .. really appreciated – youcantcme Jan 30 '19 at 13:21

1 Answers1

1

The cmp parameter to buildHeap is a function pointer which points to a function with two const void * parameters that returns an int. buildHeap can use this function pointer to call the function in question to compare two items.

For example, if you wanted to compare two integers, you would implement a function like this:

int compare_int(const void *p1, const void *p2)
{
    const int *a = p1;
    const int *b = p2;

    if (*a > *b) {
        return -1;
    } else if (*a < *b) {
        return 1;
    } else {
        return 0;
    }
}

Then you would pass compare_int as the second parameter to buildHeap, i.e. buildHeap(arr, compare_int, n). Then somewhere in buildHeap it can call this function as appropriate:

void buildHeap (void **ar, int(*cmp)(const void *,const void *), int n) {    
   ...
   cmp(ar[x], ar[y]);
   ...
}

And calling cmp inside of buildHeap actually calls compare_int.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • thanks.. as i guessed. appreciate u took the time to break it down. – youcantcme Jan 30 '19 at 13:23
  • @youcantcme Glad I could help. Feel free to [accept this answer](https://stackoverflow.com/help/accepted-answer) if you found it useful. – dbush Jan 30 '19 at 13:34