开发者

How to call pointer to function defined in typedef struct

what is wrong with the following code?

parseCounter1() and parseCounter1() below are two functions.

I p开发者_高级运维ut their pointers in const OptionValueStruct so that

they can be called accordingly when each element of option_values[]

are gone through:

typedef struct OptionValueStruct{  
    char counter_name[OPTION_LINE_SIZE];  
    int* counter_func;  
} OptionValueStruct_t;  

const OptionValueStruct option_values[] = {    
    {"Counter1", (*parseCounter1)(char*, char**)},  
    {"Counter2", (*parseCounter2)(char*, char**)},  
   };  

const OptionValueStruct *option = NULL;

for(int i = 0; i< sizeof(option_values)/sizeof(OptionValueStruct_t); i++){
    option = option_values + i ;  
    result = option->counter_func(opt_name, opt_val);  
}  


You have declared your counter_func member to be a pointer to an int, not a function pointer , while you have something resembling a function pointer declaration in your option values. Here's what you want (assuming your return type is int )

typedef struct OptionValueStruct{
  char counter_name[OPTION_LINE_SIZE];
  int (*counter_func)(char*, char**);
} OptionValueStruct_t;

const OptionValueStruct_t option_values[] = {
  {"Counter1", parseCounter1},
  {"Counter2", parseCounter2},
};

for(int i = 0; i< sizeof(option_values)/sizeof(OptionValueStruct_t); i++){
  result = option_values[i]->counter_func(opt_name, opt_val); 
  // don't know what you relly want to do with result further on..
}


If you are compiling as C code (as your tag suggests), then you should change the type of option_values[] and option to OptionValueStruct_t. In C++, however, this is OK.

Alternatively, you can eliminate the trailing _t from the custom type name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜