-
questions about pointers
hey guys, im kind of new in c and i have two questions, first what is the void * v[] for? second what is the "comp" in this line? "int (*comp)(void *,void *);" its part of an example program for qsort...is it casting of some kind?
appreciate any help.
-
1) It is an array of pointers that point to a void (can point to anything). So v[1] is a pointer, v[3] is also a pointer (a *void)
2) It is a function pointer that points to a function that is like int fun(void *, void* )
Example:
Code:
int fun(void* a, void* b)
{
...
return 0;
}
int (*comp)(void*, void*);
comp = &fun; //comp will point to fun
comp(a, b); //like fun(a,b)
-
comp is a pointer to a function returning int
v is an array of void pointers
-
"int (*comp)(void *,void *);" is a function pointer. One use for that is so you can include a function as a parameter to another function:
Code:
#include <stdio.h>
void one() {
printf("Function one\n");
}
void two() {
printf("Function two\n");
}
void dowhat (void (somefunction)()) {
somefunction();
}
int main() {
dowhat(one);
dowhat(two);
return 0;
}
I've never used C's qsort but apparently you can pass it your own comparison function, which accepts two pointers (to the things to compare) and returns an int.