2015-09-30 55 views
1

對C完全陌生,只是試圖通過獲得John Bentley的Anagram(我相信第2列)程序來運行Linux和C編程。很確定,我逐字複製了這段代碼(不得不添加頭文件等),但是我收到了一個警告,這個警告在我的squash.c程序編譯和運行時會產生不希望的輸出。生病承認,我甚至不知道這個charcomp函數如何表現,甚至它甚至沒有。 (有些啓發也會很好)。當試圖運行Anagram(John Bentley-Programming Pearls)時發出警告-C

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

int charcomp(char *x, char *y) {return *x - *y;} 

#define WORD_MAX 100 
int main(void) 
{ 
     char word[WORD_MAX], sig[WORD_MAX]; 
     while (scanf("%s", word) != EOF) { 
       strcpy(sig, word); 
       qsort(sig, strlen(sig), sizeof(char), charcomp); 
       printf("%s %s\n", sig, word); 
     } 
     return 0; 
} 

這是警告。

sign.c:13:41: warning: incompatible pointer types passing 'int (char *, char *)' 
     to parameter of type '__compar_fn_t' (aka 'int (*)(const void *, const 
     void *)') [-Wincompatible-pointer-types] 
       qsort(sig, strlen(sig), sizeof(char), charcomp); 
                 ^~~~~~~~ 
/usr/include/stdlib.h:766:20: note: passing argument to parameter '__compar' 
     here 
        __compar_fn_t __compar) __nonnull ((1, 4)); 
           ^
+0

http://linux.die.net/man/3/qsort –

+1

Programming Pearls as language introductory book?奇怪的。 – zubergu

回答

4

qsort()功能需要一個比較函數作爲第四個參數,具有以下特徵:

int (*compar)(const void *, const void *) 

因此,爲了避免編譯器警告,必須修改charcomp()功能通過以下方式,以適應該簽名:

int charcomp(const void *x, const void *y) { return *(char *)x - *(char *)y; } 

charcomp功能只需要兩個char*指針並比較他們的第一個字符。