我正在研究指针,我复制了一个快速排序实现.当我编译时,gcc 显示错误:
I'm studying pointers, and I copied a quicksort implementation. When I compile, gcc shows the error:
条件表达式中的指针类型不匹配
pointer type mismatch in conditional expression
调用错误的行是:
qSort((void**)lineptr, 0, nlines-1, (int(*)(void*, void*))(numeric ? numcmp : strcmp));该代码中的类型与初始化的类型相同:
The types in that code are the same as the initialized types:
void qSort(void *lineptr[], int left, int right, int (*comp)(void *, void *));这是 numcmp 实现:
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; } 推荐答案有问题的条件表达式是这样的:
The conditional expression in question is this:
numeric ? numcmp : strcmp编译器抱怨子表达式numcmp 的类型与子表达式strcmp 的类型不同.前者的类型为int(*)(char *, char *),后者的类型为int (*)(const char *, const char *)(提供你已经记住了 #include ,这是你必须做的).它们不相同,甚至不兼容(在标准意义上的兼容"一词).
The compiler is complaining that the type of the sub-expression numcmp is different from the type of the sub-expression strcmp. The former has type int (*)(char *, char *), and the latter has type int (*)(const char *, const char *) (provided that you have remembered to #include <string.h>, which you must do). These are not the same, nor even compatible (in the standard's sense of the term "compatible").
您可能可以通过将 const 限定符添加到函数 numcmp() 的参数来绕过该错误.然而,GCC 可能仍会抱怨您对表达式的值执行的强制转换.
You could probably get get around the error by adding const qualifiers to the parameters of function numcmp(). GCC may still complain about the cast you perform on the expression's value, however.
更多推荐
条件表达式中的指针类型不匹配
发布评论