Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding function pointers

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?

like image 407
Alex Avatar asked Dec 26 '22 01:12

Alex


2 Answers

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.

like image 71
Grijesh Chauhan Avatar answered Jan 08 '23 12:01

Grijesh Chauhan


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

like image 22
StoryTeller - Unslander Monica Avatar answered Jan 08 '23 13:01

StoryTeller - Unslander Monica