Reputation: 137
here is C code from the book "The C programming language":
#include <stdio.h>
#include <string.h>
#define MAXLINES 5000 /* max #lines to be sorted */
char *lineptr[MAXLINES]; /* pointers to text lines */
int readlines(char *lineptr[], int nlines);
void writelines(char *lineptr[], int nlines);
void qsort(void *lineptr[], int left, int right,
int (*comp)(void *, void *));
int numcmp(char *, char *);
/* sort input lines */
main(int argc, char *argv[])
{
int nlines;
int numeric = 0; /* number of input lines read */
if (argc > 1 && strcmp(argv[1], "-n") == 0) /* 1 if numeric sort */
numeric = 1;
if ((nlines = readlines(lineptr, MAXLINES)) >= 0) {
qsort((void**) lineptr, 0, nlines-1, // MY QUESTION: WHY lineptr IS CAST TO POINTER TO A VOID POINTER
(int (*)(void*,void*))(numeric ? numcmp : strcmp));
writelines(lineptr, nlines);
return 0;
} else {
printf("input too big to sort\n");
return 1;
}
}
void qsort(void *v[], int left, int right,
int (*comp)(void *, void *))
{
int i, last;
void swap(void *v[], int, int);
// rest of code
}
Why when qsort function is called first argument is being cast to pointer to a void pointer (void **) and not just to pointer to void (void *) . Please tell me why is it so?
Thanks
Upvotes: 2
Views: 979
Reputation: 1
Here, theqsort
function defines an int (*comp)(void *, void *)
parameter and *comp
is a function pointer that can be used to call a function of the comparison. Even they don't have the same function name (comp
and numcmp
), it's still valid.
Upvotes: 0
Reputation: 10057
Compilers will warn you these days unless you cast non-void pointers to void pointers when you pass them as void pointers (if that made any sense). I think you knew that, though.
The signature of void **lineptr
is equivalent in C to void *lineptr[]
, which is the type of pointer that qsort
takes as an argument. See this site for more details.
Upvotes: 1