如何调用指向typedef结构中定义的函数的指针

如何调用指向typedef结构中定义的函数的指针

问题描述:

以下代码有什么问题?
下面的parseCounter1()和parseCounter1()是两个函数.
我将他们的指针放在const OptionValueStruct中,这样
当option_values []
的每个元素都可以相应地调用它们 通过:

what is wrong with the following code?
parseCounter1() and parseCounter1() below are two functions.
I put 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);  
}  

您已经声明counter_func成员是一个指向int的指针,而不是一个函数指针,而您在option values.这就是您想要的(假设您的返回类型为int)

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..
}