【发布时间】: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 而不是 variables。
int a; printf("%d\n", (int)3.14);将编译并输出3但int a; printf("%d\n", (a)3.14);不会。 -
函数指针不一定适合
void *。因此,出于可移植性的原因,代码具有未定义的行为 - UB。建议使用union而不是void *。 -
我投票重新提出这个问题,因为它(现在)完全清楚问题是什么,并且应该给用户一个正确的答案。
标签: c function-pointers