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=; while( memcmp(fun[i].pName,"nul_func",) != )
{
if( memcmp(p,fun[i].pName,strlen(fun[i].pName)) == )
{
*pfunc = fun[i].pFunc;
return ;
}
i++;
} printf("%s\n","No Such Func.");
return ;
} int test1(int a, int b)
{
printf("a = %d, b = %d\n",a,b);
return ;
} int test2(int a, int b, int c)
{
printf("a = %d, b = %d , c = %d\n",a,b,c);
return ;
} int test3(int a, int b,int c,int d)
{
printf("a = %d, b = %d, c = %d, d = %d\n",a,b,c,d);
return ;
} int nul_func()
{
printf("%s\n","No Such Func");
return ;
}

主函数:14.c

#include<stdio.h>

int main()
{
int i;
int (*pFunc)();
char caName[] = ""; memcpy(caName,"test1",);
i = GetFunc(caName,&pFunc);
printf("%s\n",caName);
i = (*pFunc)(,); memcpy(caName,"test2",);
i = GetFunc(caName,&pFunc);
printf("%s\n",caName);
i = (*pFunc)(,,); memcpy(caName,"test3",);
i = GetFunc(caName,&pFunc);
printf("%s\n",caName);
i = (*pFunc)(,,,); return ;
}

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

结果:./test

上一篇:【转】oracle null


下一篇:[Leetcode] Search In Rotated Sorted Array (C++)