I am trying to learn about void pointers and functions that have a typedef (in C). I can't seem to grasp the concept.
I have this simple code:
#include <stdio.h>
typedef int (*CompareFunc)(void*, void*);
int compareints(void *a, void *b)
{
return a-b;
}
int comparedbls(void *a, void *b)
{
return a-b;
}
int main()
{
int a = 1, b = 1;
int* ptrA = &a;
int* ptrB = &b;
CompareFunc test = compareints;
printf("%d\n", test(ptrA, ptrB));
return 0;
}
The output here is "-4". I don't understand why. I know it's some kind of casting that I'm not doing because I feel like I am subtracting addresses. I would print the values of void *a and void *b with printf("%d", a) to see what values they have, but it says it can't because a is a void pointer.
And with the CompareFunc function, would I have to make a new variable to point to every function I want? I am not quite sure in what case using a typedef on a pointer function would ever be useful. Why not just call compareints() directly? Asking because I have an assignment and can't figure out why we need to code it like this.
Any help would be appreciated. Thank you!
%pto print yourvoid*s. Your output of-4is unsurprising and you will see why once you print the addresses. You use function pointers so that you can store or pass around pointers to functions, or interchange functions with the same signature (e.g. see stdlib'sqsort()for an example of where they are useful)%p, very handy.qsort()function — trying to use a comparator helpful.