This article includes three examples about pointers to function.
These three examples are received from the page: A good place about pointers and some topics of C. and ,of course, they are modified a bit to run for a xc164cm microcontroller.
They are all included in one .C file , the main.c file.
EXAMPLE 1 : We have a pointer ptr to a function whose parameter is void and returning a pointer to an integer.
EXAMPLE 2 : We have a pointer ptr to a function whose parameter is a character that returns an integer (this is int find(char c) ),because Ptr is equal to the return of function ().
But function () whose parameter is void returns the address of a function (&find, a pointer's value), whose function the parameter is a character that returns an integer.
EXAMPLE 3 : We have a pointer ptr to a function whose parameters are a pointer to an integer and a pointer to a float and whose return value is a pointer to a character (a string).
The c code for the examples is here.
Open Hyperterminal at 19,200 kbaud run the code and watch the result here.
Exercise : Build the example 4 of the above mentioned page by yourself.
Help: Becarefull! By default, strings are saved in flash memory space. Search Keil page to find the solution.
EXAMPLE 5 This is a universal form of the bubble sort example included in Ted Jensen's tutorial, page 50.
To give a universal form to bubble () in order to be able to sort any data type we have to insert in it a pointer to a function fptr , declaring it as:
void bubble (..., int(*fptr)( ... ) );
Having in mind that the name of a function decays into the address of that function (a function pointer value) we can call bubble() writing bubble(... , compare_long); or writing
bubble(... , compare_string);
The C code The result
EXAMPLE 6 This is a function pointer array example.
Making arrays whose elements are function pointers is a case of interest. We can call functions indexing them.
At this example we make an array of four function pointers declaring it as:
float (*fp) (float x , float y);
Each one of the pointed functions includes as arguments a float x and a float y and returns a float.
We call the function pointed by the i th element of the array writing (*fp[i])(c,d) or fp[i](c,d) where c and d are floats.
The C code The result