Having function pointer inside struct will be useful for certain data structures such as binary search tree.
Lets say , i want to insert an element whose struct is
struct Employee {
int eid;
char *name;
};
into a binary search tree. but i would like the BST to use my function to compare the elements while storing and searching.
and the bst struct will be as follows.
struct BST {
struct _node *root;
int (*compare)(void *e1 , void *e2);
};
Now, i will use the BST as follows.
int main(void){
struct Emp e1 = { 1, "John" };
struct BST *t = create_tree();
t->set_compare( &compare );
t->insert(e1);
t->get(e1);
...
}
int compare(void *e1 , void *e2)
{
//type cast e1, e2 as struct Emp
// return the comparison result based on id
}
The advantage i see is i don't need to keep on pass this function pointer into my all BST operation functions .
but storing all public functions inside struct will bring the OOP style inside C code , like what others says.