我必须使用下面的结构在C中编写一个前缀计算器,但我不知道如何使用回调来完成。我的主要疑虑是在"构建"列表后如何访问值,以及如何将值分配给指向函数的指针。
typedef struct node
{
enum type_node type;
union
{
int val;
int (*func)(struct node *x);
struct node *sublist;
} info;
struct no *next;
} node, *ptr_node;
下面的代码大多是无意义的,实际上什么都不做。然而,它很可能会编译,并显示访问结构的方法,以及使用函数指针调用函数的方法。
#include <stdio.h>
enum type_node
{
VALUE,
FUNCTION,
STRUCTURE
};
typedef struct node
{
enum type_node type;
union
{
int val;
int (*func)(struct node *x);
struct node *sublist;
} info;
struct node *next;
} node, *ptr_node;
int myfunc(struct node *someNode)
{
int rCode;
printf("type: %dn", someNode->type;
switch(someNode->type)
{
case VALUE:
printf("value: %dn", someNode->info.val);
break;
case FUNCTION:
rCode=(*someNode->info.func)(someNode);
break;
case STRUCTURE:
printf("value: %dn", someNode->info.val);
printf("func: %pn", someNode->info.func);
printf("sublist: %pn", someNode->sublist);
printf("next: %pn", someNode->next);
break;
};
return(0);
}
int main(void)
{
ptrNode np;
int rCode;
node n1 =
{
.type = VALUE,
.info.val = 2,
.next = NULL
};
node n2 =
{
.type = FUNCTION,
.info.func = myfunc,
.next = &n1
};
node n3 =
{
.type = STRUCTURE,
.info.sublist = &n2,
.next = NULL
};
np = &n1;
n1->next = &n3;
printf("np->type: %dn", np->type);
printf("n1.type: %dn", n1.type);
printf("n1.info.val: %dn", n1.info.val);
printf("np->info.val: %dn", np->info.val);
np = &n2;
rCode=(*np->info.func)(np);
rCode=(*n2.info.func)(np);
return(0);
}