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" should behave similarly to "1". Why the function pointer behaves differently. Or am I missing something?

+4
source share
5 answers

p=f2; error due to incompatible types. f2 is a function that can return int* , while p is a pointer to a function that can point to a function returns int , for example. f1()

for int* f2() , you can define a pointer to a function, as shown below:

  int* (*p2)(); // pointers to function f2 p2 = f2; 

In addition, you do not need to use & in front of the function name, just the function name is enough. Here is a good read link: Why are all these crazy definitions of function pointers all working? What is really going on?

Edit :
For a while, &functionname and functionname do not match, for example. sizeof(functionname) not valid , while sizeof(&functionname) works fine.

+3
source
 int* f2(){} 

A function that takes nothing and returns a pointer to int .

 int (*p)(); 

Pointer to: A function that takes nothing and returns int

You have a type mismatch. p not a pointer to type f2

If you have trouble understanding definitions like all mortals, use the spiral rule

+3
source

This is a function that returns int*

 int* f2(){} 

So you need to:

 (int*) (*q)(); q = f2; 
+2
source

p is a pointer to a function that takes the value void and returns an integer.

f1 is a function that takes a void value and returns an integer.

f2 is a function that takes a void argument and returns a pointer to an integer.

Now, according to the definitions, you can see that f1 can be assigned to p , but f2 can't. To assign f2 to p , the declaration of p must be int *(*p)();

+1
source

You made the wrong assignments, i.e. incompatible types

For functions

 int f1(){} int* f2(){} 

The correct appointments will be

 int (*p)(); p = f1; int* (*p)(); p = f2; 
+1
source

Source: https://habr.com/ru/post/1489093/


All Articles