Results 1 to 2 of 2
Hi,
what is the actual use of function pointer and at which stage is useful.
what is the difference , by calling the function directly instead of thru function pointer.
...
- 05-14-2007 #1Linux Newbie
- Join Date
- Oct 2006
- Posts
- 107
function pointer
Hi,
what is the actual use of function pointer and at which stage is useful.
what is the difference , by calling the function directly instead of thru function pointer.
how we will distinguish these ...........
Pls help me.....
- 05-14-2007 #2
Function pointers are useful in that they allow us to pass around functions, which enables a certain level of abstraction. For instance, imagine the following:
Which gives the following output:Code:#include <stdio.h> static void printfirst(char *s) { putchar(s[0]); putchar('\n'); } static void printsecond(char *s) { putchar(s[1]); putchar('\n'); } void doToArray(char **strings, int length, void (*func)(char *)) { int i; for(i = 0; i < length; i++) func(strings[i]); } int main() { char *strings[] = { "hello", "goodbye", "hi there!", "testing", "yohoho" }; puts("I will now print the FIRST letter of each string"); doToArray(strings, 5, printfirst); putchar('\n'); puts("I will now print the SECOND letter of each string"); doToArray(strings, 5, printsecond); return 0; }
So you see how I can write a single function that does something to every element of an array, and what it does is determined by the function I give it.Code:alex@danu ~/test/c $ ./a.out I will now print the FIRST letter of each string h g h t y I will now print the SECOND letter of each string e o i e o
I could use a similar thing to sort a list of structs using different comparisons (say, if we have a struct that contains file information, we could sort by filename, by inode, by type, etc.). Or maybe I use it to copy a list of void pointers, where the person who made the list passes me the function to use for each individual copy.
See how this works?DISTRO=Arch
Registered Linux User #388732


Reply With Quote