KARTHIK BHAT
KARTHIK BHAT

Reputation: 1400

K&R C function pointer

I was reading K&R book (first time) I came across a function using pointers.

Function call

qsort(
    (void **)lineptr,
    0,
    nlines-1,
    (int (*)(void *,void *)) (numeric ? numcmp : strcmp)
);

What I understood is that based on the numeric either the address of strcmp or numcmp is passed and the address is type casted to (int (*)(void *,void *)) as required for the function.

Function defintion

void qsort(void *v[],int left,int right, int (*comp)(void *, void *))

So is my interpretation correct regarding the function pointer??

Upvotes: 2

Views: 807

Answers (1)

unwind
unwind

Reputation: 400159

Yes, that's right.

The cast is needed since strcmp() takes const char * arguments, but they are safe to convert to void *.

If you look at the current manual page for qsort() you can see that the callback's arguments should really be const void *, not just void * but that's a safe conversion too (as long as the callback treats the pointer as pointer to const, of course).

Upvotes: 5

Related Questions