尝试运行 Anagram 时出现警告(John Bentley-Programming Pearls)-C

avc*_*Jav 1 c qsort

对 C 完全陌生。只是想通过运行 John Bentley 的 Anagram(我相信是第 2 列)程序来掌握 Linux 和 C 编程的窍门。很确定我逐字复制了这段代码(必须添加标头等),但我收到一条警告,当使用我的 squash.c 程序编译和运行时,会给出不需要的输出。承认吧,我什至不知道这个 charcomp 函数的行为方式,或者它的作用。(那里的一些启发也很好)。

#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;
}
Run Code Online (Sandbox Code Playgroud)

这是警告。

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));
                                 ^
Run Code Online (Sandbox Code Playgroud)

syn*_*gma 5

qsort()函数采用比较函数作为第四个参数,具有以下签名:

int (*compar)(const void *, const void *)
Run Code Online (Sandbox Code Playgroud)

因此,为了避免编译器警告,您必须charcomp()按以下方式修改函数以适应该签名:

int charcomp(const void *x, const void *y) { return *(char *)x - *(char *)y; }
Run Code Online (Sandbox Code Playgroud)

您的charcomp函数只需要两个char*指针并首先比较它们的第一个字符。