Home > OS >  How to pass a function pointer of an function pointer array as function parameter in C?
How to pass a function pointer of an function pointer array as function parameter in C?

Time:12-17

I have an array of function pointer

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

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

I would to call the ledOnOff function, passing for example pwmCallPointer[0] to call the callRED function

How should the prototype be? This one is not working:

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

The call will be for example:

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

CodePudding user response:

How should the prototype be?

The fifth parameter of ledOnOff() function should be pointer to a function which takes an argument of type int and returns an int. So, the prototype should be:

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

For better readability:

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]);

CodePudding user response:

You've discovered the correct syntax already when defining the pointer array:

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

A typedef can make the whole stuff easier:

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

Note that there's an alternative variant:

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

allowing to declare void ledOnOff(Callback cb); – I personally prefer the former variant, though, for not hiding the pointer nature of variables or parameters.

Side note: Your original variant

void ledOnOff(pwmCallPointer*);

failed to compile because pwmCallPointer does not name a type, but a global variable. The type of the function pointer is int(*)(int), and int(*ptr)(int) declares a variable or parameter just as char* ptr would, solely the syntax is more complicated. You could even name it pwmCallPointer – just as the global array. Be aware, though, that you then have two distinct variables (the global one and the local parameter) which just share the same name, and within the function the global variable is hidden by the local one. Doing so, of course, is not recommendable.

  • Related