Home > Enterprise >  C Struct with pointer to the function?
C Struct with pointer to the function?

Time:04-28

Can anybody explain what is written in this structure in C

struct Structure {
  int i;
  void (*function)(struct Structure*);    
 } ;

CodePudding user response:

As @jonathen-leffler has described in comments, the structure has 2 members. The first member in the structure holds an integer value. The second member is a function pointer, the function takes an input argument of `a pointer to struct Structure' and returns nothing.

so, the 2nd member can point to a function that is declare as below,

void someWork(struct Structure* someStruct)
{
  //do some work on struct
  someStruct->i = 5;
}

To declare and initialize a struct of this type, do as below,

 struct Structure myStruct;
 myStruct.i=400;
 myStruct.function = &someWork;

To make it easier to refer to the function pointer , typedef can be used, like so :

 typedef void (*func)(struct Structure*);

 //assign it as
 func = &someWork;

CodePudding user response:

Here's a "working example":

#include <stdio.h>

struct Structure {
    int i;
    void (*function)(struct Structure *);
};

void foo(struct Structure *);
void bar(struct Structure *);

int main(void) {
    struct Structure a = {0, foo};
    struct Structure b = {42, NULL}; // don't call b.function() just yet!!
    a.function(&b);
    b.function(&a);
}

void foo(struct Structure *a) {
    if (a->function == NULL) a->function = bar;
    printf("value from foo: %d\n", a->i);
}

void bar(struct Structure *a) {
    printf("value from bar: %d\n", a->i);
}
  • Related