cstructfunction-pointerspicxc8

Trying to call function using a void pointer inside a variable type


In the firmware that I am writing, I created a type of variable. Similar to what is below:

    struct SitemMenu {
      unsigned int id;
      char * text;
      void * submenu
    }
    typedef struct SitemMenu TitemMenu;

Be any function:

    void functionX () {
      ...
    }

If I create this variable:

    TitemMenu itemWhatever;

and do:

    itemWhatever.submenu = &function (X);

Can I call functionX doing:

    (*itemWhatever.submenu)();

I did something similar to this and the compiler give this answer:

    error: (183) function or function pointer required

Solution

  • Yes you can, but not quite the way you've written it.
    A function pointer is not declared in quite the same way as a 'normal' pointer.
    What you need is:

    struct SitemMenu {
      unsigned int id;
      char * text;
      void (* submenu)(void); // this is a function pointer, as opposed to the 'normal' pointer above
    };
    
    typedef struct SitemMenu TitemMenu;
    TitemMenu itemWhatever;
    

    then, if you have some function declared with the same parameters and return type, like:
    void functionX(void), then you can do:

    itemWhatever.submenu = functionX;
    itemWhatever.submenu();