Detailed description of C ++ function pointers and function pointers
1. function pointer
(1) In general, a function usually includes a series of commands. After compilation, it occupies a block of storage space in the memory.
It has a starting address, which is called a function pointer.
(2) When the main function calls a subfunction, it is to transfer the program to the function entry address for execution.
(3) we can define a pointer variable to point to the function, and then call this function by using this pointer variable.
Pointer to a function: A pointer variable that can store a function entry address.
To sum up, the function pointer has two purposes: one is to call a function, and the other is to make a function parameter.
The general form of function pointer definition:
Data Type (* pointer variable name) (parameter table );
For example:
Int (* p) (); // p is the pointer to the function whose return value is integer data.
Float (* q) (float, int); // q is a pointer to a function that returns floating point data.
2. function pointer call procedure
(1) The function pointer variable must first point to the Function
If you define a pointer variable pointing to a function, you can establish an association between the pointer variable and a specific function to point the pointer variable to a specific function.
Note:
(1) pointer variables can only point to the class of functions specified at the time of definition.
(2) A pointer variable can point to multiple different functions successively.
Code:
# Include <stdio. h>
Int arr_add (int (* arr) [4], int n, int m)
Void main ()
{
Int a [3] [4] = };
Int * p, total1, total2;
Int (* pt) (int (* arr) [4], int n, int m );
Pt = arr_add;
Total1 = arr_add (a, 3,4 );
Total2 = (* pt) (a, 3, 4 );
Printf ("total1 = % d, total2 = % d \ n", total1, total2 );
}
Int arr_add (int (* arr) [4], int n, int m)
{
Int I, j, sum = 0;
For (I = 0; I <n; I ++)
For (j = 0; j <m; j ++)
Sum + = arr [I] [j];
Return (sum );
}