gpt4 book ai didi

c - 指向函数 : can't compile 的指针

转载 作者:太空宇宙 更新时间:2023-11-04 00:19:46 24 4
gpt4 key购买 nike

#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*'

最佳答案

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

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

关于c - 指向函数 : can't compile 的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2037674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com