2010-01-10 57 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函數所要求的相同的簽名,然後在裏面輸入參數。