C 如何在当前上下文中定义函数指针?
嘿,如果给我以下定义,我对如何定义函数指针有点困惑:C 如何在当前上下文中定义函数指针?,c,linked-list,function-pointers,C,Linked List,Function Pointers,嘿,如果给我以下定义,我对如何定义函数指针有点困惑: struct menu_item { char name[ITEM_NAME_LEN+1]; BOOLEAN (*func)(struct vm*); }; 我使用下面的函数menu init定义了menu_项包含的初始变量。假设此函数定义菜单项数组的每个成员 void menu_init(struct menu_item * menu) { strcpy(menu[0].name, "\t1. Display I
struct menu_item
{
char name[ITEM_NAME_LEN+1];
BOOLEAN (*func)(struct vm*);
};
我使用下面的函数menu init定义了menu_项包含的初始变量。假设此函数定义菜单项数组的每个成员
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 */
}
打印列表的声明如下
void print_list(struct vm_node *root);
任何帮助都将不胜感激 这是创建和分配(在同一行中…)函数指针的示例
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
也会起作用,而且还有其他几种方法可以实现相同的结果
关于您的代码,您可以像我在上面的示例中那样,分配
菜单[0].func=print\u list代码>如果打印列表是一个布尔返回函数。相反,您将其定义为void returning函数 如果您有一个结构菜单项变量
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) ;
你的语法错了
最简单的修复方法是通过更改函数使其具有与函数指针匹配的适当类型来摆脱强制转换:
BOOLEAN print_list(struct vm_node *root);
然后你可以做:
menu[0].func = print_list;
请注意,这更有意义,因为通过func
函数指针调用的代码需要BOOLEAN
返回值,因此强制它使用并通过强制转换调用不匹配的函数不是一个好主意。您能澄清一下您在语法方面有什么问题吗。基本上,我不太确定我将如何声明它,这样当我使用menu->func时,它将调用print_list函数并打印整个列表。请注意,print_list
函数和struct menu\u item
中的函数指针成员有不同的参数列表和返回类型?除此之外,您只需将函数分配给结构中的成员func
。