Prashanth said:
#include<string.h>
void (*foobar)();
void main()
{
char *str;
strcpy(str,"Fun1");
strcat(str,"method1");
foobar= ( Here i should get the address of Fun1method1 function through "str")
(*foobar)();
}
void Fun1Method1()
{
printf("Here ... I am !!!");
}
Can any one please help with this ....
Your code has a number of problems.
Firstly, main returns int, not void, so change the return type, and
add return 0; at the end of main.
Secondly, you're missing a prototype for printf, so add <stdio.h>
to your list of includes.
Thirdly, you reserve no storage for the target of your strcpy and
strcat.
Fourthly, you'll need a prototype for Fun1Method1().
Fifthly, I think you meant to strcat "Method1", not "method1".
Sixthly, it's a good idea to add a \n to your printf, to make
sure the output appears when you expect it to.
Let's solve those problems, and answer your question at the same
time.
#include <stdio.h>
#include <string.h>
void (*foobar)();
void Fun1Method1(void);
int main(void)
{
char str[12]; /* big enough for "Fun1Method1" */
strcpy(str, "Fun1");
strcat(str, "Method1");
if(strcmp(str, "Fun1Method1") == 0)
{
foobar = Fun1Method1;
(*foobar)();
}
return 0;
}
void Fun1Method1(void)
{
printf("Here ... I am !!!\n");
}
If you have many such functions, you may wish to consider
constructing a lookup table, comprised of structs containing
a string with the function name, and a pointer to the
appropriate function:
struct VOID_FUNCTION_VOID_LOOKUP
{
char Name[32]; /* based on the maximum unique identifier length
* guaranteed by ISO C90.
*/
void (*Function)(void);
};
Construct an array of these structures, populate the array,
and sort it by name (see qsort). You can then use bsearch
to find the right entry in the array, and dereference the
pointer you get (if it isn't NULL) to get a pointer to the
appropriate struct. Then it's just a matter of accessing
the Function member of the struct.