c - C 中具有不同返回类型和参数的函数指针数组

标签 c function-pointers

我有 3 个具有不同返回类型和不同参数的函数。我正在尝试创建一个函数指针数组,然后调用它们。但它不起作用。请提供一些建议。

#include <stdio.h>

/* Array of function pointers (different return types and parameters) */

void sayHello()
{
    printf("Hello World\n");
}

int add(int a, int b)
{
    return a+b;
}

int twice(int a)
{
    return 2*a;
}

int main()
{
    int choice;
    int(*add_ptr)(int,int) = NULL;
    void(*hello_ptr)(void) = NULL;
    int(*twice_ptr)(int) = NULL;

    void * func_table[] = {(void *)sayHello, (void *)add, (void *)twice};


    printf("Add : %d\n", ((add_ptr)func_table[1])(10,5));
    printf("Hello : \n",((hello_ptr)func_table[0])());
    printf("Twice : %d\n",((twice_ptr)func_table[2])(10));
    return 0;
}

编辑

我已将代码编辑为如下所示:

#include <stdio.h>

/* Array of function pointers (different return types and parameters) */

void sayHello()
{
    printf("Hello World\n");
}

int add(int a, int b)
{
    return a+b;
}

int twice(int a)
{
    return 2*a;
}

int main()
{
    int choice;
    typedef int(*add_ptr)(int,int);
    typedef void(*hello_ptr)(void);
    typedef int(*twice_ptr)(int);

    void * func_table[] = {(void *)sayHello, (void *)add, (void *)twice};


    printf("Add : %d\n", ((add_ptr)func_table[1])(10,5));
    printf("Hello : ",((hello_ptr)func_table[0])());
    printf("Twice : %d\n",((twice_ptr)func_table[2])(10));
    return 0;
}

但我仍然收到错误:

error: invalid use of void expression
  printf("Hello : ",((hello_ptr)func_table[0])());
  ^

最佳答案

您似乎希望 add_ptrhello_ptrtwice_ptr 成为函数指针类型(因为您'重新转换为它们)而不是变量:

typedef int(*add_ptr)(int,int);
typedef void(*hello_ptr)(void);
typedef int(*twice_ptr)(int);

或者,如果您打算将 add_ptrhello_ptrtwice_ptr 作为变量并分配 func_table 的元素code> 到这些变量,然后:

add_ptr = func_table[1];
hello_ptr = func_table[0];
twice_ptr = func_table[2];
printf("Add : %d\n", add_ptr(10,5));
printf("Hello : "); hello_ptr();
printf("Twice : %d\n", twice_ptr(10));
<小时/>

此外,您不需要在此处强制转换为 void*:

void * func_table[] = {sayHello, add, twice};
<小时/>

此外,您的零参数函数 sayHellomain 在其参数列表中缺少关键字 void。它们应该看起来像这样:

void sayHello(void) { … }
int main(void) { … }

关于c - C 中具有不同返回类型和参数的函数指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37276284/

相关文章:

c - 使用 'system(...)' 从程序启动命令提示符

c - C错误中的LinkedList

c - 左值需要作为函数指针赋值的左操作数

通过main调用另一个函数来打开文件

更改指针地址 - 函数

c - 在 C 中如何处理缓冲区

C 编程术语

c - 重新附加到 Linux 中的进程

c++ - 使用 Cereal 序列化 Lambda 函数

c - 使用 Union 中存在的函数指针执行 shell 代码