Wednesday, October 21, 2009

C a prg of fun point

Following code demonstrates the usage of 'C' function pointer. It may not be a great one but simple to understand..

#include
#include

int cmd_show()
{
printf("Show \n");
return 0;
}
int cmd_add()
{
printf("Add \n");
return 0;
}

/* command structure*/
typedef struct {
char name[100];
int (*exec_cmd)();
} cmd_t;

cmd_t cmd_table1[] = {
{"cmd_show", cmd_show},
{"cmd_add", cmd_add}
};

/* A Function that is returning the function pointer
* the syntax would be - return_type (*function_name(param_list of this))(argument_type of the fun ptrs)
*/
int (*get_func(char *str))()
{
int i = 0;
for (i = 0; i < sizeof(cmd_table1)/sizeof(cmd_t); i++)
{
if (strcpy(cmd_table1[i].name, str)) {
printf("Matched!\n");
return cmd_table1[i].exec_cmd;
}
}
return NULL;
}

int main()
{
int (*exec_fun)();
/* call the get func, it returns the function address based on the string passed */
exec_fun = get_func("cmd_show");
if (exec_fun != NULL)
return exec_fun();
return 0;
}

No comments:

Post a Comment