首页 > 解决方案 > 如何解决函数指针的这个错误?

问题描述

在一个程序中,一个指针被声明为函数 (p),该函数被初始化为函数 (add)

我试图阅读与函数指针相关的所有概念。但我无法解决它请帮我解决这个程序没有任何错误。

#include <stdio.h>
#include <iostream>
using namespace std;

int add(int n1, int n2) 
{
    return n1 + n2;
}

int *functocall(int,int);
int caller(int n1, int n2, int(*functocall)(int, int))
{
    return (*functocall)(n1, n2);
}

int main() 
{
    int a, b, c;
    cin >> b >> c;

    int (*p)(int,int)=&add;
    a=caller(b,c,(*functocall)(b,c));
    printf("%d",a);

    return 0;
}

如果输入是 20 70 输出必须是 90

标签: c++

解决方案


(*functocall)(b,c)不符合您的预期,您正在尝试调用functocall. (注意,它functocall被声明为一个函数,它接受两个ints 并返回一个int*。)

您应该将函数指针本身传递给caller,例如

a = caller(b, c, p);

或者

a = caller(b, c, &add);

居住


推荐阅读