函数指针实例

#include <stdio.h>

char arraysearch(int data)
{
//some code
    return (data+2);
}
char linkedlistsearch(int data)
{
//some code
    return (data-2);
}
char binarysearch(int data)
{
//some code
    return (data * 2);
}
char search( char (*funcptr)( int ), int data )
{
    return (*funcptr)(data);
}

int main(int argc, char* argv[])
{
    printf("Input Options\n");
    printf("1 arrsrch\n");
    printf("2 linkedlistsrch\n");
    printf("3 binarysrch\n");
    printf("4 exit\n");
    int choice = 0;
    int data;
    int ret = 0;
    
    while(choice != 4)
    {
        printf("Input choice:\n");
        scanf("%d", &choice);
        if(choice == 4)
        {
            printf("goodbye!\n");
            break;
        }           
        
        printf("Data to search\n");
        scanf("%d", &data);

        if(choice == 1)
        {
            ret = search(arraysearch,data); //invoking 1st function
        }
        else if(choice == 2)
        {
            ret = search(linkedlistsearch, data); //invoking 2nd function
        }
        else if(choice == 3)
        {
            ret = search(binarysearch, data); //invoking 3rd function
        }
        
        
        printf("ret = %d\n", ret);
    }
    return 0;
}

 

posted @ 2018-09-09 22:15  wdliming  阅读(407)  评论(0编辑  收藏  举报