int f1(){}
int* f2(){}
int main()
{
int *a;//1
int b;
int *c;
a=c;
a=&b;
int (*p)(); //2
p=f2; //showing error
p=&f1;
}
I expected that in my program '2' must behave similar to '1'. Why function pointer are behaving differently. Or am I missing something?
p=f2;
error because incompatible types. f2
is a function that can return a int*
whereas p
is pointer to function that can point to a function returns int
e.g. f1()
for int* f2()
, you can defined a pointer to function as below:
int* (*p2)(); // pointers to function f2
p2 = f2;
Additionally, you don't need to use &
before function name just function name is enough.
Here is a good link to read: Why do all these crazy function pointer definitions all work? What is really going on?
Edit:
Some time &functionname
and functionname
are not same e.g. sizeof(functionname)
is not valid whereas sizeof(&functionname)
is perfectly valid.
int* f2(){}
A function that accepts nothing, and returns a pointer to an int.
int (*p)();
A pointer to: A function that accepts nothing and returns an int
You have a type mismatch. p
is not a pointer to the type of f2
If you have trouble understanding such definitions, like all mortal do, use the spiral rule of thumb
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