【问题标题】:pointers to functions: can't compile指向函数的指针:无法编译
【发布时间】:2010-01-10 16:45:55
【问题描述】:
#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*' 

【问题讨论】:

  • 要回答您的直接问题,您很可能正在将代码编译为 C++。
  • 不,事实并非如此。上帝,我在 K&R 的第 5 章,在大约 500 个项目之后,我已经知道这两个之间的差异了 :)
  • @Tool:我在这里没有看到任何编译时错误:codepad.org/SW2QOGhI
  • 而且...如果你看起来更好,22 C:\Users\SUZI\Desktop\solutions\Chapter 5\Exercise 5-14\sort.c 表示 sort.c 是一个 c 程序。
  • 对函数指针使用 typedef 也是个好主意

标签: c pointers function


【解决方案1】:

您正在使用 ANSI C 编译器而不是老式的 K&R C 编译器进行编译。

错误信息很清楚,看const不匹配。将您的函数更改为具有与 qsort 函数所需的签名相同的签名,然后将参数转换为内部。

【讨论】:

    【解决方案2】:

    尝试将第 22 行更改为:

    qsort((void **) lineptr, 0, nlines - 1, (numeric ? (int (*)(void *, void *))numcmp : (int (*)(void *, void *))strcmp));
    

    【讨论】:

    • 成功了,谢谢 :) 哦,顺便说一句,我使用的是 Dev-C++,但编译为 C 项目。
    • 看来Dev C拒绝原程序是错误的?
    • 你为什么要使用一个 5 年以上没有维护的软件,它很糟糕,即使它是 i> 维护?请获取合适的编译器/IDE。
    • 因为 atm,对我来说编程只有教育目的。
    • 还有其他免费选项供你选择:Mingw、lcc-win32,我认为微软的visual C是免费的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多