Find the answer to your Linux question:
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. ...
  1. #1
    Linux 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.....

  2. #2
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    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:
    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;
    }
    Which gives the following output:
    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
    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.

    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...