【问题标题】:pointer to function wont work指向函数的指针不起作用
【发布时间】:2015-04-14 17:18:24
【问题描述】:

我正在尝试学习如何使用指针来正常工作。我应该在函数check 内部创建一个指向函数strcmp 的指针,但程序会立即打开和关闭。据我了解,我的代码returnType (*pointer)(parameters)); 上的函数指针是正确的那么出了什么问题?提前致谢。

void check(char *a,char *b,int (*cmp)(const char*,const char*))
{
    printf("Testing equality\n");
    if(!(*cmp)(a,b)) printf("equals");
    else printf("different");
}

int main(void)
{
    char s1[80] = "daniel" ,s2[80] = "daniel";
    int (*p)(const char*,const char*);
    p = strcmp();


    check(s1,s2,p);

    return 0;
}

【问题讨论】:

  • 编译器没有警告过你这个p = strcmp();吗?
  • 哪个编译器编译成功p = strcmp();?而怎么做?
  • 您是否自己添加了strcmp 的声明以使其编译? (你可以直接说check(s1, s2, strcmp)。)

标签: c++ c pointers function-pointers


【解决方案1】:

此行不正确:

p = strcmp();

在这里,您使用零参数调用 strcmp,这是无效的。你应该已经得到了一个非常明确的编译器错误。例如,gcc 给了我:

错误:函数“int strcmp(const char*, const char*)”的参数太少

你只想分配 strcmp:

p = strcmp;

另外,您不需要取消引用函数指针来调用它们,因此!(*cmp)(a,b) 可以简化为!cmp(a,b)

【讨论】:

  • 是的,这本书的教学方式,应该是 p = strcmp;没有 (),但代码块不允许我,所以我添加了 (),并得到警告 |10|警告:赋值使指针从整数不进行强制转换 [默认启用]|
  • 与 p = strcmp;错误是:“strcmp 未声明”
  • @DanielBezerradeMenezes 你#include <cstring>了吗?
  • 天哪,我太笨了,对不起伙计们,问题是#includes并排............就像#include #include.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-22
  • 2020-06-30
  • 1970-01-01
  • 1970-01-01
  • 2011-04-26
  • 1970-01-01
相关资源
最近更新 更多