Description of function pointers
A pointer can point to a variable, an array, or a function. A function pointer is a pointer to a function. The function name is actually the starting address of the program in the memory. The pointer to the function can pass the address to the function, or return the pointer to the function from the function. For example, a function is used to calculate the sum of two numbers and call the function through the function pointer.
# Include <stdio. h> int sum (int a, int B); // Declaration of the summation function void main () {int a, B; int (* fun) (int, int ); // declare a function pointer printf ("enter two integers:"); scanf ("% d, % d", & a, & B ); printf ("the first method to call a function: the function name calls the sum function: \ n"); printf ("% d + % d = % d \ n", a, B, sum (a, B); // call fun = sum through the function name; // The function pointer points to the summation function printf ("the second method to call a function: function pointer calls the summation function: \ n "); printf (" % d + % d = % d \ n ", a, B, (* fun) (, b); // call the function through the function pointer} int sum (int m, int n) // implement the {return m + n ;}
The program running result is as follows:
The statement int (* fun) (int, int) in the program is to declare a pointer variable pointing to the function, and the return value of the function to be pointed to is an integer, there are two integer parameters. Statement fun = sum; indicates that the function pointer fun points to the sum function. both fun and sum point to the start address of the sum function. during compilation, the program is translated into a line of commands and loaded into the memory area. As shown in:
The statements (* fun) (a, B) in the main function are used to call the sum function. They can also be written as fun (a, B, because the function itself is an address.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.