Always feel that the function pointer is a difficult thing, in fact, the function pointer and the general pointer, quite simple.
One, the definition of a function pointer
A function pointer, as the name implies, is a pointer to a function, which is a pointer to the start address of the function storage area. Let's take a look at how it is declared:
Char* (*PF) (char *,char *);
This statement declares a pointer to a function that has two character pointers and returns a character pointer.
Sometimes it's easy to mistake a function pointer and a general function declaration, such as:
Char *fun (Char *,char *), Char **fun (char *,char *);
The first statement declares a function that has two character pointer parameters and also returns a character pointer. Note that the difference between this statement and the previous one is that the function pointers are enclosed in parentheses.
The second statement also declares a function that returns a pointer to a pointer.
Sometimes the situation is very complex, as long as from the innermost analysis, careful point should be able to analyze what is the statement.
Second, the use of function pointers
The use of a function pointer is the same as a normal forehead pointer, which is assigned after the declaration and then runs the function with the (*) symbol. The following is a simple example:
#include <stdio.h> #include <string.h>char* fun (char *a,char *b) {if (strlen (a) >=atrlen (b)) {return A;} Else{return b;}} int main () {char* (*PF) (char *,char *); char *p;pf=&fun;<span style= "White-space:pre" ></span>// can also be directly used Pf=fun to assign value p= (*PF) ("111", "ten"); Use the (*) number to run the function printf ("%s\n", p); return 0;}
Three: array of function pointers
As well as the normal array of pointers, here is a small example:
#include <stdio.h>char *fun1 (char *a) {printf ("%s\n", a); return A;} Char *fun2 (char *a) {printf ("%s\n", a); return A;} Char *fun3 (char *a) {printf ("%s\n", a); return A;} int main () {char* (*pf[3]) (char *a);p f[0]=&fun1;<span style= "White-space:pre" ></span>//to assign values sequentially pf[1]= &fun2;pf[2]=&fun3;pf[0] ("AA");p f[1] ("BB");p f[2] ("CC"); return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
function pointers in the C language