views:

191

answers:

2
#include <stdio.h>
#include <string.h>

#define MAXLINES 5000
char *lineptr[MAXLINES];

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 *);

int main(int argc, char *argv[])
{
    int nlines;
    int numeric = 0;

    if(argc > 1 && strcmp(argv[1], "-n") == 0)
       numeric = 1;
    if((nlines = readlines(lineptr, MAXLINES)) >= 0) {
        qsort((void **) lineptr, 0, nlines - 1, (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);

     if(left >= right)
        return;

     swap(v, left, (left + right) / 2);
     last = left;
     for(i = left + 1; i <= right; i++) 
        if((*comp)(v[i], v[left]) < 0)
           swap(v, ++last, i);
     swap(v, left, last);
     qsort(v, left, last - 1, comp);
     qsort(v, last + 1, right, comp);
}

This is direct source code from K&R, in chapter pointers and functions, and this is the example they showed about pointers to functions, but i just cant compile the line in which i call QSORT(line 22). I get this:

22 C:\Users\SUZI\Desktop\solutions\Chapter 5\Exercise 5-14\sort.c conditional expression between distinct pointer types `int (*)(char*, char*)' and `int (*)(const char*, const char*)' lacks a cast 

22 C:\Users\SUZI\Desktop\solutions\Chapter 5\Exercise 5-14\sort.c invalid conversion from `int (*)(char*, char*)' to `void*' 

22 C:\Users\SUZI\Desktop\solutions\Chapter 5\Exercise 5-14\sort.c invalid conversion from `int (*)(const char*, const char*)' to `void*' 
+6  A: 

You are compiling with an ANSI C compiler instead of a good-old K&R C compiler.

The error message is quite clear, look at the const mismatches. Change your function to have the same signature as the qsort function requires, and then cast the arguments inside.

bmargulies
+5  A: 

Try changing line 22 to:

qsort((void **) lineptr, 0, nlines - 1, (numeric ? (int (*)(void *, void *))numcmp : (int (*)(void *, void *))strcmp));
codaddict
This did it, thanks :) Oh and by the way, im using Dev-C++, but compiling as a C project.
Tool
Looks like Dev C is wrong in rejecting the original program then?
Alok
Why would you use a piece of software that hasn't been maintained for 5+ years, **and** which sucked and was horribly buggy even when it *was* maintained? Please, get a proper compiler/IDE.
jalf
Cause atm, programming for me has only an educational purpose.
Tool
There are other free options for you: Mingw, lcc-win32, and I think Microsoft's visual C is free.
Alok