C Interview Questions and Answers

 

If I have a char * variable pointing to the name of a function ...

If I have a char * variable pointing to the name of a function, how can I call that
function? Code like



extern int func(int, int);



char *funcname = "func";



int r = (*funcname)(1, 2);





or



r = (*(int (*)(int, int))funcname)(1, 2);





doesn't seem to work.





By the time a program is running, information about the names of its functions and
variables (the ``symbol table'') is no longer needed, and may therefore
not be available. The most straightforward thing to do, therefore, is to maintain
that information yourself, with a correspondence table of names and function pointers:



int one_func(), two_func();



int red_func(), blue_func();





struct { char *name; int (*funcptr)(); } symtab[] = {


"one_func", one_func,


"two_func", two_func,


"red_func", red_func,


"blue_func", blue_func,



};





Then, search the table for the name, and call via the associated function pointer,
with code like this:



#include <stddef.h>



int (*findfunc(char *name))()



{



int i;





for(i = 0; i < sizeof(symtab) / sizeof(symtab[0]); i++) {



if(strcmp(name, symtab[i].name) == 0)



return symtab[i].funcptr;



}





return NULL;



}





...



char *funcname = "one_func";



int (*funcp)() = findfunc(funcname);



if(funcp != NULL)



(*funcp)();

Posted by:Richards