简体   繁体   English

将函数数组作为函数的参数传递

[英]Passing array of functions as argument to function

My C is a bit rusty. 我的C有点生锈。 Suppose I have the following 假设我有以下内容

char* (*funcs[n])(void);

How would I define or declare another function to take this array as parameter. 我将如何定义或声明另一个函数将此数组作为参数。 I tried with 我尝试过

void func(char* (*p)(void));

But gcc complains. 但是海湾合作委员会抱怨。

The parameter has the same type as the array, except that you can omit the size: 该参数与数组具有相同的类型,但可以省略大小:

void print(char* (*p[])(void)) { ... }

You can also use the fact that the array decays into a pointer and declare: 您还可以使用数组衰减为指针的事实并声明:

void print(char* (**p)(void)) { ... }

These function signatures are equivalent. 这些功能签名是等效的。 In the function, call the function with either of these: 在函数中,使用以下任一函数调用函数:

char *a = (*p)();
char *b = (p[0])();

These calls are equivalent, too. 这些调用也是等效的。

But, as user694733 points out in the comments, everything is made easier by making a typedef for functions of a certain signature, say: 但是,正如user694733在注释中指出的那样,通过为特定签名的函数创建一个typedef ,一切将变得更加容易,例如:

typedef char *(*Charpfunc)(void);

Then you can just use the familiar syntax for your arrays and function parameters: 然后,您可以对数组和函数参数使用熟悉的语法:

char *hello(void) { return "hello"; }
char *howdy(void) { return "howdy"; }
char *goodbye(void) { return "goodbye"; }

typedef char *(*Charpfunc)(void);

void print(Charpfunc *p)
{
    while (*p) {
        puts((*p)());
        p++;
    }
}

int main()
{
    Charpfunc funcs[] = {
        hello, howdy, goodbye, NULL
    };

    print(funcs);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM