【问题标题】:How to pass a function pointer of an function pointer array as function parameter in C?如何在C中将函数指针数组的函数指针作为函数参数传递?
【发布时间】:2022-01-20 09:58:47
【问题描述】:

我有一个函数指针数组

int callRED(int); //func 1
int callGREEN(int); //func2 
int callBLUE(int); //func3

int (*pwmCallPointer[3])(int) = {callRED, callGREEN, callBLUE }; //array of function pointer

我会调用 ledOnOff 函数,例如传递 pwmCallPointer[0] 来调用 callRED 函数

原型应该是怎样的? 这个不工作:

void ledOnOff(int, int, int, int, pwmCallPointer*);

调用将是例如:

ledOnOff(0, 0, 0, 0, pwmCallPointer[0])

【问题讨论】:

  • void ledOnOff(int, int, int, int, int(*)(int))

标签: c pointers function-pointers


【解决方案1】:

原型应该是怎样的?

ledOnOff() 函数的第五个参数应该是指向一个函数的指针,该函数接受int 类型的参数并返回int。所以,原型应该是:

void ledOnOff(int, int, int, int, int (*fptr) (int));
                                  ^^^^^^^^^^^^^^^^^

为了更好的可读性:

typedef int (*fptr) (int); // fptr is an alias of type int (*) (int)

// Declare array of function pointers of type fptr
fptr pwmCallPointer[] = {callRED, callGREEN, callBLUE};

// ledOnOff prototype
void ledOnOff(int, int, int, int, fptr);

// call it like this
ledOnOff(0, 0, 0, 0, pwmCallPointer[0]);

【讨论】:

    【解决方案2】:

    在定义指针数组时,您已经发现了正确的语法:

    void ledOnOff(int(*pwmCallPtr  )(int));
    // just omitting the array   ^^
    // declaration
    

    typedef 可以让整个事情变得更简单:

    typedef int(Callback)(int);
    void ledOnOff(Callback* cb);
    

    请注意,还有另一种变体:

    typedef int(*Callback)(int);
    //          ^
    

    允许声明void ledOnOff(Callback cb);——不过,我个人更喜欢前一种变体,因为它不会隐藏变量或参数的指针性质。

    旁注:您的原始变体

    void ledOnOff(pwmCallPointer*);
    

    编译失败,因为pwmCallPointer 没有命名一个类型,而是一个全局变量。函数指针的类型为int(*)(int)int(*ptr)(int)声明变量或参数的方式和char* ptr一样,只是语法比较复杂。你甚至可以将它命名为pwmCallPointer——就像全局数组一样。但是请注意,您有两个 distinct 变量(全局变量和局部参数),它们只是共享相同的名称,并且在函数内,全局变量被局部变量隐藏。当然,不建议这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      • 2020-11-08
      • 2019-08-17
      • 2015-01-29
      • 2013-01-25
      • 2021-10-05
      • 2012-11-23
      相关资源
      最近更新 更多