Pointer to function

(1) Function pointer

Definition: if a function is defined in the program, the compilation system allocates a storage space for the function code at compile time. The starting address of this storage space is called the pointer of this function.

(2) Calling functions with function pointer variables

Small example, take the maximum value

#include<stdio.h>
int main(){
    int max(int x,int y);
    int (*p)(int,int);   //Define pointer variables to functions p 
    int a=0,b=0,c=0;
    p=max;
    scanf("%d%d",&a,&b);
    printf("%d %d\n",a,b);
    c=(*p)(a,b);    //Called by pointer variable max function 
    printf("%d",c);
}

int max(int x,int y){
    int z;
    if(x>y) z=x;
    else z=y;
    return(z);
}

As you can see, the general format for defining pointer variables to functions
Type name (* pointer variable name) (function parameter list)
Int (* P) (int, int) P is a pointer variable to a function. It can only point to the entry of the function, not to an instruction in the middle of the function

(3) Point to function pointer as parameter

For example, when the user enters two numbers a and B, when the user enters 1, the maximum value of the two numbers is taken; when the user enters 2, the minimum value of the two numbers is taken; when the user enters 3, the sum of the two numbers is taken

Define a fun function. Each time you pass the entry address of a different function name as an argument to a parameter in the fun function (that is, a pointer to the function)

 1 #include<stdio.h>
 2 int main(){
 3     int fun(int x,int y,int(*p)(int,int));  //fun Function declaration 
 4     int max(int,int);
 5     int min(int,int);
 6     int add(int,int);
 7     int a,b,n;
 8     scanf("%d%d",&a,&b);
 9     printf("Select 1, 2, 3\n");
10     scanf("%d",&n);
11     if(n==1) fun(a,b,max);  //Called on input 1 max function 
12     else if(n==2) fun(a,b,min);  //When entering 2 min function 
13     else if(n==3) fun(a,b,add);  //Input 3 call add function 
14     return 0; 
15 } 
16 int fun(int x,int y,int (*p)(int,int)){
17     int result;
18     result=(*p)(x,y);
19     printf("%d\n",result);
20 }
21 int max(int x,int y){ //Take the maximum value
22     int z;
23     if(x>y) z=x;
24     else z=y;
25     return(z);
26 }
27 int min(int x,int y){  //Take the minimum value
28     int z;
29     if(x<y) z=x;
30     else z=y;
31     return(z);
32 }
33 int add(int x,int y){  //Find the sum of two numbers
34     int z;
35     z=x+y;
36     return(z);
37 }

Keywords: C

Added by kcomer on Fri, 01 May 2020 23:43:46 +0300