2010-01-10 59 views
1
#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); 
} 

这源自K & [R直接的源代码,在章指针和功能,这是他们表现出对函数指针的例子,但我不能编译我称其为QSORT(第22行)。我得到这个:函数指针:不能编译

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*' 
+1

要回答你的问题直接,最有可能你正在编译代码为C++。 – 2010-01-10 16:49:28

+0

不,不是这种情况。上帝,我在K&R的第5章,我知道这两个之间的差异,大约500个项目后:) – Tool 2010-01-10 16:50:06

+0

@Tool:我没有看到任何编译时错误在这里:http://codepad.org/SW2QOGhI – 2010-01-10 16:51:46

回答

5

尝试改变线22:

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

这样做,谢谢:)哦,顺便说一下,即时通讯使用Dev-C++,但作为一个C项目编译。 – Tool 2010-01-10 17:02:33

+0

看起来像Dev C在拒绝原始程序时是错误的呢? – 2010-01-10 17:07:41

+0

为什么你会使用一个未被维护5年以上的软件,**和**,这些软件甚至在被维护时都会被吸引,并且是非常可怕的。请获得一个合适的编译器/ IDE。 – jalf 2010-01-10 17:24:55

6

您与ANSI C编译器,而不是一个好老K & R C编译器进行编译。

错误信息非常明确,请看const不匹配。改变你的函数,使其具有与qsort函数所要求的相同的签名,然后在里面输入参数。