如何将函数指针数组传递给另一个函数

How to pass array of function pointers to another function

本文关键字:函数 另一个 指针 数组      更新时间:2023-10-16

我有两个函数:

char* odwroc(char* nap, int n) 
char* male(char* nap, int n) 

我定义了一个指向的指针

 typedef char*(*pointerToFunction )( char*, int );

然后在主要使用该定义:

 pointerToFunction ptr1 = odwroc;
 pointerToFunction ptr2 = male;

但现在我必须创建一个函数,该函数作为第一个参数,获取指向该函数的指针数组,我就陷入了困境。我不知道如何定义指向函数的指针数组,也不知道modyfikuj参数列表应该是什么样子。

void modyfikuj(char* pointerToFunction *pointerArray, int length, char* nap2, int n){ 
}

试试这个:

pointerToFunction mojefunkcje[] = { odwroc, male};
modyfikuj( mojefunkcje, ...);      // pass the array fo modyfikuj()
void modyfikuj( pointerToFunction* funtab, ...)
{
    funtab[0]( string, liczba);    // call  odwroc( string, liczba)
    funtab[1]( string, liczba);    // call  male( string, liczba)
}

尽管上面的答案是有意义的,但在传递类似类型的数组(如指向函数的指针)时,使用std::vector等容器将为您提供更多的控制。请尝试下面的代码片段。

#include "vector"
using namespace std;
typedef char*(*pointerToFunction )( char*, int );
typedef vector<pointerToFunction> FUNCTION_VECTOR;
bool modyfikuj( FUNCTION_VECTOR& vecFunctionVector )
{
    // The below checking ensures the vector does contain at least one function pointer to be called.
    if( vecFunctionVector.size() <= 0 )
    {
        return false;
    }
    // You can have any number of function pointers to be passed and get it executed, one by one.
    FUNCTION_VECTOR::iterator itrFunction = vecFunctionVector.begin();
    FUNCTION_VECTOR::const_iterator itrFunEnd = vecFunctionVector.end();
    char* cszResult = 0;
    for( ; itrFunEnd != itrFunction; ++itrFunction )
    {
        cszResult = 0;
        // Here goes the function call!
        cszResult = (*itrFunEnd)( "Hello", 1 );
        // Check cszResult for any result.
    }
    return true;
}
char* odwroc(char* nap, int n); // You will define this function somewhere else.
char* male(char* nap, int n); // You will define this function somewhere else.
int main()
{
    FUNCTION_VECTOR vecFunctions;
    // You can push as many function pointers as you wish.
    vecFunctions.push_back( odwroc );
    vecFunctions.push_back( male );
    modyfikuj( vecFunctions );
    return  0;
}