How to use function pointers in a structure in C?

This is pretty simple what I'm trying to do, and it's just hard for me to understand the correct syntax.

I want my structure to look like this:

struct myStruct { functionPointer myPointer; } 

Then I have another function somewhere else that passes the function to the function and returns an instance of my structure. Here is what he does:

 struct myStruct myFunction(int (*foo) (void *)) { myStruct c; c.myPointer = foo; return c; } 

How can I make this work? What is the correct syntax for:

  • Declaring a function pointer in my structure (obviously functionPointer myPointer; incorrect)
  • Assigning an address of a function to a pointer to this function (pretty true c.myPointer = foo is wrong)?
+4
source share
2 answers

This really is no different from any other function pointer instance:

 struct myStruct { int (*myPointer)(void *); }; 

Although it would often be possible to use typedef to remove this a bit.

+3
source

More or less:

 struct myStruct { struct myStruct (*myPointer)(int (*foo)(void *)); }; typedef struct myStruct myStruct; 

c.myPointer should be fine, but you need to return a copy of the structure, not a pointer to the current local variable c .

 struct myStruct { struct myStruct (*myPointer)(int (*foo)(void *)); }; typedef struct myStruct myStruct; struct myStruct myFunction(int (*foo) (void *)) { myStruct c; c.myPointer = foo; return c; } 

This compiles, but the compiler (reasonably) complains that foo not exactly the right type. So the problem is that this is the correct type for the function pointer in the structure? And it depends on what you want.

0
source

Source: https://habr.com/ru/post/1390941/


All Articles