【问题标题】:Array of function pointers in C with different return types and arguments [closed]C中具有不同返回类型和参数的函数指针数组
【发布时间】:2016-09-13 13:30:56
【问题描述】:

我有 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])());
  ^

【问题讨论】:

  • "但它不起作用" - 请解释 什么 不起作用。
  • 您只能转换为 types 而不是 variablesint a; printf("%d\n", (int)3.14); 将编译并输出 3int a; printf("%d\n", (a)3.14); 不会。
  • 函数指针不一定适合void *。因此,出于可移植性的原因,代码具有未定义的行为 - UB。建议使用union 而不是void *
  • 我投票重新提出这个问题,因为它(现在)完全清楚问题是什么,并且应该给用户一个正确的答案。

标签: c function-pointers


【解决方案1】:

您似乎希望 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 的元素分配给这些变量,那么:

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) { … }

【讨论】:

  • 是的。我需要typedef吗?为什么?我很困惑....
  • typedef void(*hello_ptr)(void); 应该是typedef void(*hello_ptr)();,对吧?
  • @CoolGuy 应该是voidsayHellomain 的声明在其参数列表中缺少 void
  • @InsaneCoder 因为您想将add_ptr(等)声明为类型,而不是变量。或者,您可能只想将 func_table[1] 分配给 add_ptr 变量。其语法为add_ptr = func_table[1];
  • @tuple_cat 是的。那也行。我建议在您的回答中提及它。
猜你喜欢
  • 1970-01-01
  • 2015-04-18
  • 2014-05-12
  • 1970-01-01
  • 1970-01-01
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多