Function pointer in C

How can I create a "function pointer" (and (for example, a function has parameters) in C?

+3
source share
6 answers

http://www.newty.de/fpt/index.html

typedef int (*MathFunc)(int, int); int Add (int a, int b) { printf ("Add %d %d\n", a, b); return a + b; } int Subtract (int a, int b) { printf ("Subtract %d %d\n", a, b); return a - b; } int Perform (int a, int b, MathFunc f) { return f (a, b); } int main() { printf ("(10 + 2) - 6 = %d\n", Perform (Perform(10, 2, Add), 6, Subtract)); return 0; } 
+15
source
  typedef int (*funcptr)(int a, float b); funcptr x = some_func; int a = 3; float b = 4.3; x(a, b); 
+5
source

I found this site useful when I first dived into function pointers.

http://www.newty.de/fpt/index.html

0
source

First declare a pointer to a function:

 typedef int (*Pfunct)(int x, int y); 

Almost the same as the function prototype.
But now all you have created is a function pointer type (with typedef ).
So now you are creating a pointer to a function of this type:

 Pfunct myFunction; Pfunct myFunction2; 

Now assign the addresses of the functions to these, and you can use them the way they are:

 int add(int a, int b){ return a + b; } int subtract(int a, int b){ return a - b; } . . . myFunction = add; myFunction2 = subtract; . . . int a = 4; int b = 6; printf("%d\n", myFunction(a, myFunction2(b, a))); 

Function pointers are great fun.

0
source

In addition, we can create an array of pointers for the function:

 double fun0(double x, double y) { return x + y; } double fun1(double x, double y) { return x - y; } double fun2(double x, double y) { return x / y; } int main(int argc, char*argv[]) { const int MaxFunSize = 3; double (*funPtr[MaxFunSize])(double, double) = { fun0, fun1, fun2 }; for(int i = 0; i < MaxFunSize; i++) printf("%f\n", funPtr[i](2.5, 1.1)); return 0; } 
0
source

You can also define functions that return function pointers:

 int (*f(int x))(double y); 

f is a function that takes a single parameter int and returns a pointer to a function that takes a double parameter and returns int.

0
source

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


All Articles