• linux c函数指针的应用


    头文件:1.h

    #include<stdio.h>
    
    int nul_func();
    int test1(int a,int b); 
    int test2(int a,int b,int c); 
    int test3(int a,int b,int c,int d); 
    int GetFunc(char *p,int (**pfunc)());
    
    struct test
    {
        char *pName;
        int  (*pFunc)();
    }fun[] = { 
    
        {"test1",test1},
        {"test2",test2},
        {"test3",test3},
        {"nul_func",nul_func}
    
    };

    函数实现:15.c

    #include "1.h"
    #include <string.h>
    
    int GetFunc(char *p,int (**pfunc)())
    {
        int i=0;
    
        while( memcmp(fun[i].pName,"nul_func",8) != 0)
        {   
            if( memcmp(p,fun[i].pName,strlen(fun[i].pName)) == 0 ) 
            {   
                *pfunc = fun[i].pFunc;
                return 0;
            }   
            i++;
        }   
        
        printf("%s
    ","No Such Func.");
        return 0;
    }
    
    int test1(int a, int b)
    {
        printf("a = %d, b = %d
    ",a,b);
        return 0;
    }
    
    int test2(int a, int b, int c)
    {
        printf("a = %d, b = %d , c = %d
    ",a,b,c);
        return 0;
    }
    
    int test3(int a, int b,int c,int d)
    {
        printf("a = %d, b = %d, c = %d, d = %d
    ",a,b,c,d);
        return 0;
    }
    
    int nul_func()
    {
        printf("%s
    ","No Such Func");
        return 0;
    }


    主函数:14.c

    #include<stdio.h>
    
    int main()
    {
        int i;
        int (*pFunc)();
        char caName[10] = ""; 
        
        memcpy(caName,"test1",5);
        i = GetFunc(caName,&pFunc);
        printf("%s
    ",caName);
        i = (*pFunc)(1,2);
    
        memcpy(caName,"test2",5);
        i = GetFunc(caName,&pFunc);
        printf("%s
    ",caName);
        i = (*pFunc)(3,4,5);
    
        memcpy(caName,"test3",5);
        i = GetFunc(caName,&pFunc);
        printf("%s
    ",caName);
        i = (*pFunc)(6,7,8,9);
    
        return 0;
    }

    编译:gcc 14.c 15.c -o test

    结果:./test

  • 相关阅读:
    PHP递归函数
    php算法
    php 设计模式
    TP5与TP3.X对比
    TP中U配置使用及CRUD
    smarty
    javascript运行机制之执行顺序详解
    让nodeJS支持ES6的词法----babel的安装和使用
    node.js + express 初体验【hello world】
    GIT-查看config配置信息
  • 原文地址:https://www.cnblogs.com/sherlockhomles/p/4806665.html
Copyright © 2020-2023  润新知