I was trying to figure out function pointers. My code looks like this I have a file.h where I have a struct that hast 2 members
typedef struct _node_ {
char* string;
int (*compare)(int a, int b);
} node
in that same file, I have a prototype for a function called:
void init_with_function_pointer(node* list, int (*comp)(int x, int y));
then in my file.c, I define the function :
void init_with_function_pointer(node* list, int (*comp)(int x, int y)){
node_init(list);
list->compare = comp;
}
and in my main.c
int main(){
node tree;
init_with_function_pointer(&tree, /* what should I pass here */)
}
And that function that I need to point to should be defined in file.c
but I can't get it to work, if I define the function in main and a pass it, then it works, but if I try to use extern for that same function which I define in file.c the compiler tells me comp is not defined.
and this is my function that i would like to point to:
extern int comp(int x,int y) {
if (x < y) {
return -1;
} else if(x == y) {
return 0;
} else {
return 1;
}
}
Can someone help me?
You need a prototype for the comp function in file.h:
int comp(int, int);
Then in main() you write:
init_with_function_pointer(&tree, comp);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With