条件表达式中的指针类型不匹配

编程入门 行业动态 更新时间:2024-10-14 14:18:00
本文介绍了条件表达式中的指针类型不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在研究指针,我复制了一个快速排序实现.当我编译时,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.

更多推荐

条件表达式中的指针类型不匹配

本文发布于:2023-11-22 14:39:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617841.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   指针   不匹配   条件   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!