【问题标题】:How to define a function pointer in the current context?如何在当前上下文中定义函数指针?
【发布时间】:2014-10-14 06:44:33
【问题描述】:

如果给定以下定义,我对如何定义函数指针有点困惑:

struct menu_item
{
    char name[ITEM_NAME_LEN+1];
    BOOLEAN (*func)(struct vm*);

};

我使用以下函数 menu_init 定义 menu_item 包含的初始变量的方式。这个函数假设定义了菜单项数组的每个成员。

void menu_init(struct menu_item * menu)
{
    strcpy(menu[0].name, "\t1. Display Items");
    menu[0].func = (*void)&print_list(struct vm_node node); //print list is suppose to print the entire linked list past to the function print_list. Though i am unsure if this is correct. 

    strcpy(menu[1].name,"\t2. Purchase Items");
    strcpy(menu[2].name,"\t3. Save and Exit");
    strcpy(menu[3].name, "\t4. Add Item");
    strcpy(menu[4].name,"\t5. Remove Item");
    strcpy(menu[5].name,"\t6. Display Coins");
    strcpy(menu[6].name, "\t7. Reset Stock");
    strcpy(menu[7].name,"\t8. Reset Coins");
    strcpy(menu[8].name,"\t9. Abort Program");

  /* The UNUSED() function is designed to prevent warnings while your 
     * code is only partially complete. Delete this function call once 
     * you are using vm in your own code */
}

print_list的声明如下。

void print_list(struct vm_node  *root);

任何帮助将不胜感激。

【问题讨论】:

  • 你能澄清一下你有什么问题吗?
  • 只是语法。基本上我不确定我将如何声明它,以便当我使用 menu->func 时它会调用 print_list 函数并打印整个列表。
  • 注意print_list函数和struct menu_item中的函数指针成员有不同的参数列表和返回类型?除此之外,您只需将函数分配给结构中的成员 func。

标签: c linked-list function-pointers


【解决方案1】:

你的语法错误。

最简单的解决方法是摆脱强制转换,通过将函数更改为具有正确的类型以匹配函数指针:

BOOLEAN print_list(struct vm_node *root);

那么你可以这样做:

menu[0].func = print_list;

请注意,这更有意义,因为通过func 函数指针调用的代码将期望BOOLEAN 返回值,因此强制它使用和调用不匹配的函数通过强制转换不是一个好主意。

【讨论】:

    【解决方案2】:

    如果你有一个 struct menu_item 变量

    struct menu_item m ;
    m.func = you_function_name ;
    

    这就是语法,在你的情况下是:

    void menu_init(struct menu_item * menu)
    {
        strcpy(menu[0].name, "\t1. Display Items");
        menu[0].func = print_list;
        ....
    

    你可以像其他任何函数一样调用它:

    menu[0].func( node) ;
    

    【讨论】:

      【解决方案3】:

      这是创建和分配(在同一行中)函数指针的示例

      int g(int y){return y;}
      
      int main()
      {
          int (*f)(int x) = &g; // initializing f with the address of g. f is a pointer to a function that returns int, and has 1 int parameter
          printf("%d",f(1)); // calling g, using the pointer f
          return 0;
      }
      

      现在,函数指针可以被滥用,所以f = g 代替f = &g 也可以工作,还有更多方法可以达到相同的结果。

      关于您的代码,您可以像我在上面的示例中所做的那样指定menu[0].func = print_list;,如果print_list 是一个布尔返回函数。相反,您将其定义为 void 返回函数。

      【讨论】:

        猜你喜欢
        • 2011-03-04
        • 2011-07-26
        • 1970-01-01
        • 1970-01-01
        • 2018-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多