【问题标题】:Warning when trying to run Anagram(John Bentley-Programming Pearls)-C尝试运行 Anagram 时的警告(John Bentley-Programming Pearls)-C
【发布时间】:2015-12-28 20:26:50
【问题描述】:

对 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;
}

这是警告。

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

【问题讨论】:

标签: c qsort


【解决方案1】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 2021-07-12
    • 2011-06-28
    • 2010-11-07
    • 1970-01-01
    • 2014-06-22
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    相关资源
    最近更新 更多