Hi all. Firstly, im new here and I hope during my stay I will help many people an in turn receive help from others. Ive been studying C programming for over a year now and have been reading through the K&R bible.
Anyway enough of that...
What I cant seem to understand is one of their examples. I wont post entire code but rather point out the essentials. Two functions are declared that both have the same data type arguments and same return type:
int numcmp(char *, char *);
Thus, we can use a function pointer to point to either one of them. (Because one of the main requirements of function pointers is that they point to the same function type in both return and arguments.
int strcmp(char *s, char *t)
Next, a function called qsort is used. It takes four arguments. Ignore the first three and focus on the fourth. It says that it takes in a function pointer whos local name is "comp". Its a function pointer because the name and * in front of it are together parenthesized. Further, this function pointer is one that points to a function that returns an int and expects two void arguments:
Now when this function want to be called, its coded as:
void qsort(void *lineptr, int left, int right,
int (*comp)(void *, void *));
Now my problem is ultimately the fourth parameter. I simply do not get it. I understand the
qsort((void**) lineptr, 0, nlines-1,
(int (*)(void*,void*))(numeric ? numcmp : strcmp));
part. It chooses which function to call numcmp or strcmp based on a variable called numeric. But its what is infront of it that I cannot understand and the entire internet has not given me an answer:
(numeric ? numcmp : strcmp)
Is that some sort of cast? Why does it even need to be cast?
Why void arguments? It doesnt match the the char arguments
Why the (*)? I dont even know where to begin