函数指针实例一

#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);
}
//funcptr为函数指针,函数有一个int参数,返回char
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;
}

 

猜你喜欢

转载自www.cnblogs.com/CodeWorkerLiMing/p/9622880.html