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

Warning when trying to run Anagram(John Bentley-Programming Pearls)-C

对 C 完全陌生。只是想掌握 linux 和 C 编程的窍门,方法是将 John Bentley 的 Anagram(我相信是第 2 列)程序转换为 运行。很确定我一字不差地复制了这段代码(必须添加 headers 等),但我收到了一个警告,当我的 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;
}

这是警告。

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

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

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

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

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

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