Search code examples
cstructtypedef

Function pointer in struct, taking the struct as argument in C


How can I use function pointers in a struct using the struct as argument?

I have this:

typedef struct button {
    char SizeUnit;
    char Status;
    
    int Width;
    int Height;
    
    
    char *Text;
    Color TextColor;
    Color BGColor;
    Color BorderColor;
    int BorderWidth;
    
    
    void (*ActionL)(button *bt);
    void (*ActionR)(button *bt);
    void (*ActionM)(button *bt);
    
    void (*Hover) (button *bt);
    void (*draw) (button *bt);
} button;

How can I get this working?


Solution

  • The "effects" of the typedef (the symbol being recognized) are not available in the struct itself.

    You have two options:

    1. Simply reference struct button when it comes to define function pointers

       void (*ActionL)(struct button *bt);`
      
    2. Write the typedef before the struct defintion (forward declaration):

       typedef struct button_s button_t;
      
       typedef  struct button_s {
           char SizeUnit;
           char Status;
      
           int Width;
           int Height;
      
           char *Text;
           Color TextColor;
           Color BGColor;
           Color BorderColor;
           int BorderWidth;
      
           void (*ActionL)(button_t *bt);
           void (*ActionR)(button_t *bt);
           void (*ActionM)(button_t *bt);
      
           void (*Hover) (button_t *bt);
           void (*draw) (button_t *bt);
       } button_t;
      

      Here I used a convention with a trailing _s for the struct before the typedef and _t for the newly defined type.