這裏是C代碼書「C程序設計語言」:施展無效**,爲什麼?
#include <stdio.h>
#include <string.h>
#define MAXLINES 5000 /* max #lines to be sorted */
char *lineptr[MAXLINES]; /* pointers to text lines */
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 *);
/* sort input lines */
main(int argc, char *argv[])
{
int nlines;
int numeric = 0; /* number of input lines read */
if (argc > 1 && strcmp(argv[1], "-n") == 0) /* 1 if numeric sort */
numeric = 1;
if ((nlines = readlines(lineptr, MAXLINES)) >= 0) {
qsort((void**) lineptr, 0, nlines-1, // MY QUESTION: WHY lineptr IS CAST TO POINTER TO A VOID POINTER
(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);
// rest of code
}
爲什麼當qsort函數被調用的第一個參數被強制轉換爲指向一個無效的指針(void **),而不僅僅是指針void(void *)。請告訴我爲什麼這樣?
感謝
這是'qsort'所期望的參數類型。當你傳遞'lineptr'時,它會變成'char **',編譯器應該抱怨。將指針轉換爲預期類型會關閉編譯器,因爲它會顯示「我知道我在做什麼」並將參數轉換爲正確的類型。 –