求助:指向函数的指针的引用
正在看The C programming laugage 2ndBrian W. Kernighan & Dennis M. Ritchie 写的。
看到《指向函数的指针》这一部分。对关于他的函数指针的引用感到非常困惑:
qsort1((void**) lineptr, 0, nlines-1, (int (*)(void*,void*))(numeric ? numcmp : strcmp));
划线的部分到底是应该怎么理解呢?
请大家忙帮理解一下。
程序的目的是利用函数指针来选择根据字典顺序(strcmp)来排序,还是通过(numcmp)来排序。
原书的代码如下:
程序代码:
#include <stdio.h> #include <string.h> #include <stdlib.h> #define MAXLINES 5000 char *lineptr[MAXLINES]; int readlines(char *lineptr[], int nlines); void writelines(char *lineptr[], int nlines); void qsort1(void *lineptr[], int left, int right, int (*comp)(void *, void *)); int numcmp(char *, char *); main(int argc, char *argv[]) { int nlines; int numeric = 0; int (*pointertofunc)(char *, char *); if (argc > 1 && strcmp(argv[1], "-n") == 0) numeric = 1; if ((nlines = readlines(lineptr, MAXLINES)) >= 0) { qsort1((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 qsort1(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); qsort1(v, left, last-1, comp); qsort1(v, last+1, right, comp); } int numcmp(char *s1, char *s2) { double v1, v2; v1 = atof(s1); v2 = atof(s2); if (v1 < v2) return -1; else if (v1 > v2) return 1; else return 0; } void swap(void *v[], int i, int j) { void *temp; temp = v[i]; v[i] = v[j]; v[j] = temp; }
我在编译出的结果报错如下:
程序代码:
xls@Debian:~/debian/code/c_programs$ cc pointer_to_function_error.c pointer_to_function_error.c: In function ‘main’: pointer_to_function_error.c:23: warning: pointer type mismatch in conditional expression /tmp/ccinNKUN.o: In function `main': pointer_to_function_error.c:(.text+0x4b): undefined reference to `readlines' pointer_to_function_error.c:(.text+0xa1): undefined reference to `writelines' collect2: ld returned 1 exit status
[ 本帖最后由 xiaolaoshucj 于 2011-8-10 15:54 编辑 ]