Can we define functions in structs in C programming language?
You can use only function pointers in C. Assign address of real function to that pointer after struct initialization, example:
#include
#include
struct unit
{
int result;
int (*add) (int x, int y);
};
int sumFunc(int x, int y) { return x + y; }
void *unitInit()
{
struct unit *ptr = (struct unit*) malloc(sizeof(struct unit));
ptr->add = &sumFunc;
return ptr;
}
int main(int argc, char **argv)
{
struct unit *U = unitInit();
U->result = U->add(5, 10);
printf("Result is %i\n", U->result);
free(U);
return 0;
}
Good example of using function pointers in a struct you can find here https://github.com/AlexanderAgd/CLIST Check header and then clist.c file.