如何定义函数指针数组并且函数没有相同的输入参数定义?

时间:2012-12-26 17:27:54

标签: c function pointers

是否可以定义一个函数指针数组(并且函数没有相同的输入参数),如下面的代码所示?

如果是,我必须在函数定义int (*handler)(/*what Ihave to put here ?*/);

中添加
struct handler_index {
    const char *name;
    int (*handler)(/*what Ihave to put here ?*/);
};

int handler0 (int a, int b)
{
    printf("%d\n",a+b);
}

int handler1 (int a, int b, int c)
{
    printf("%d\n",a+b+c);
}

int handler2 (int a, int b, int c, int d)
{
    printf("%d\n",a+b+c+d);
}

const struct handler_index handler_index[] = {
  [0] = {"handler0", handler0},
  [1] = {"handler1", handler1},
  [2] = {"handler2", handler3},
};

3 个答案:

答案 0 :(得分:5)

什么都不做:

int (*handler)();

这意味着该函数具有未指定(但非变量)的数量和参数类型。

任何返回int且具有固定可变数量参数的函数都可以分配给handler

答案 1 :(得分:3)

虽然int (*handler)()确实会为函数提供可变数量的参数,但我没有看到任何好处。当你有一段代码需要一些东西时,函数指针很有用,找到“正确的事情”(例如将“name”与其他地方的一些输入进行比较),并调用函数指针来做它必须做的事情。调用代码的函数指针需要知道函数有多少个参数(如何传递正确的数字和参数顺序。

我实际上根本没有看到任何有意义的使用。是的,您可以将可变数量的参数传递给函数,但代码必须知道函数采用的参数。

除非在结构的定义中以某种方式指定了参数 - 但是你需要为结构定义不同的内容以允许它。

我建议你需要考虑你想要实现的目标,然后提出解决问题的方法,最有可能使用不同的方法。

答案 2 :(得分:0)

什么也不放。只是空括号。

int (*handler)();