Pointer functions and function pointers

Function pointer

  It will be appreciated in accordance with literally: Returns the value of the function pointer.

  His is essentially a function, with other functions of the difference is that the return type of the function pointer is a pointer.

 

  for example:

int fuc(void)
{
    return 5;
}

  Fuc This function returns the value of type int and returns a value of 5.

 

  So what kind of pointer function?

int *fuc(void)
{
    return 5;
}

  This function is fuc, with the above function is different, he returned value is of type int *, that is, returns a pointer that points to the number 5 plastic int address.

  To pay attention to when using the pointer function, outgoing pointers do not point to address local variables

  such as:

int *fuc(void)
{
    int a = 5;
    return a;
}

  This example is wrong (of course, if it is not a function pointer, then this usage is not a problem)

  In this embodiment a return value of type int address, but is a local variable, then when the end of the local variable is fuc recovered, so we can not obtain this figure 5.

 

 

 

Function pointer

  The literal meaning to be understood that the function pointer is: pointers to functions.

  His is essentially a pointer, we usually use the pointer

  such as:

int a = 5;
int *p;
p = a ;

  P pointer points to an integer number a of the address, which is the deposit with the number 5.

 

  Then the function pointer to a function

int (*p)(int);

  This is the name of the function pointer p, a pointing function that returned parameter int int, or so that the expression, function type pointer p pointing to int () (int)

  

  According to my understanding, function pointers and other pointers on basic usage is the same, that is to say, the pointer name, you can replace the function name appears

int fuc(void)
{
    int a = 5;
    return a;
}

int main(int argc, char const *argv[])
{
    int (*p)(void);
    p = fuc;
    printf("%d\n", fuc());
    printf("%d\n", p());
    printf("%d\n", (*p)());
    return 0;
}

  Function pointer p points to fuc this function, so fuc () and p () is the equivalent, and p () with (* p) () is the same, so the compiler output is:

5
5
5

  Note here that if I used

    printf("%d\n", *p());

  This is the wrong usage.

 

  Since its essence is a pointer, then we can put the pointer passed as a parameter to another function

int plus(int x,int y)
{
    return x + y ;
}

int jian(int x,int y)
{
    return x - y;
}

int jisuan(int (*p)(int,int),int x,int y)
{
    return (*p)(x,y);
}

int main(int argc, char const *argv[])
{

    printf("%d\n" , Jisuan (Jian, . 1 , 2 )); 
    the printf ( " % D \ n- " , jisuan (PLUS, . 1 , 2 )); 

    return  0 ; 
}

  In this example we will int (* p) (int, int) as an argument the other functions, to achieve the purpose of using a flexible function to call other similar functions.

 

Guess you like

Origin www.cnblogs.com/qifeng1024/p/12452893.html