8

Is it possible to create a pointer to a function pointer, i.e.

int32_t (*fp[2])(void) = {test_function1, test_function_2}; // initialize a function pointer

<unknown> = fp;

What needs to be written in place of unknown? With "normal" arrays, I could do this:

int a[2] = {0, 1};

int* p = a;
8
  • Why do you declare fp as an array of function pointers, if you only want a single pointer? Commented Sep 24, 2014 at 9:34
  • As for your problem, you need to declare a variable that is a pointer to an array of function pointers, the pointer to an array is the important parts here. And if that's not what you want, then we can't help you unless you tell us what you want? And possibly why you want it (read about the XY problem). Commented Sep 24, 2014 at 9:36
  • The size of the function pointer array shall be irrelevant. Commented Sep 24, 2014 at 9:37
  • 1
    int32_t (**fpp)(void) = fp; Commented Sep 24, 2014 at 9:39
  • 1
    Have you tried just declaring <unknown> as a plain pointer to a function? Remember that arrays decays to pointers to their first element, in your case fp decays to a pointer to test_function1. Commented Sep 24, 2014 at 9:40

2 Answers 2

35
typedef void(*func_ptr_t)(void); // a function pointer

func_ptr_t* ptr_to_func_ptr;     // a pointer to a function pointer - easy to read
func_ptr_t  arr[2];              // an array of function pointers - easy to read

void(**func_ptr_ptr)(void);      // a pointer to a function pointer - hard to read
void(*func_ptr_arr [2])(void);   // an array of function pointers - hard to read
Sign up to request clarification or add additional context in comments.

2 Comments

if I have void (**foo)(int, int) as a pointer to a function pointer. How can the function pointer be use ?
3
typedef int32_t FP(void);

FP *fp[2] = { test_function1, test_function2 };
FP **p = fp;

4 Comments

Personally I would probably make the type-alias FP a pointer, but that's just a matter of personal taste. :)
@JoachimPileborg I would do that too, function pointers is about the only case where it is ok to hide a pointer behind a typedef. But I think the style in this answer is fine too, since it is consistent with the rule of never typedef:ing away a pointer.
This way you can also declare functions, e.g. FP test_function1, test_function2;
@MattMcNabb That, I would however not recommend, as it will make the reader confuse them with variables. You'd easily make the mistake of declaring a function at local scope, for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.