I’m having trouble compiling the example program presented in section 5.11 of the book. I have removed most of the code and left only the relevant stuff.
#define MAXLINES 5000 char *lineptr[MAXLINES]; void qsort1(void *lineptr[], int left, int right, int (*comp)(void *, void *)); int numcmp(char *, char *); main(int argc, char *argv[]) { int numeric = 1; /* ... */ qsort1((void**) lineptr, 0, 100, (int (*)(void*, void*))(numeric ? numcmp : strcmp)); } void qsort1(void *v[], int left, int right, int (*comp)(void *, void *)) { /* ... */ } int numcmp(char *s1, char *s2) { /* ... */ }
The problem is that the code doesn’t compile (I’m using Digital Mars compiler). The error I get is this:
qsort1((void**) lineptr, 0, nlines - 1, (int (*)(void*, void*))(numeric ? numcmp : strcmp)); ^ go.c(19) : Error: need explicit cast to convert from: int (*C func)(char const *,char const *) to : int (*C func)(char *,char *) --- errorlevel 1
There must be something wrong with the declarations although I pasted the code from the book correctly. I don’t know enough to make the right changes (the section about the function pointers could certainly have been written more extensively).
EDIT: I should have mentioned that I’m reading the ANSI version of the book.
I think the error comes from the fact that old C did not know const yet: strcmp there took two pointers to non-const characters (
char *) i think (which could be the reason why it compiled back then, but not with your compiler). However, nowadays strcmp takeschar const*(const char*is the same thing). Change your function prototype to this: