我必须使用下面的结构在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;
答案 0 :(得分:0)
以下几乎是无意义的代码,实际上并没有做任何事情。 但是,它很可能会编译,并显示访问结构的方法,并使用函数指针调用函数。
#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: %d\n", someNode->type;
switch(someNode->type)
{
case VALUE:
printf("value: %d\n", someNode->info.val);
break;
case FUNCTION:
rCode=(*someNode->info.func)(someNode);
break;
case STRUCTURE:
printf("value: %d\n", someNode->info.val);
printf("func: %p\n", someNode->info.func);
printf("sublist: %p\n", someNode->sublist);
printf("next: %p\n", 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: %d\n", np->type);
printf("n1.type: %d\n", n1.type);
printf("n1.info.val: %d\n", n1.info.val);
printf("np->info.val: %d\n", np->info.val);
np = &n2;
rCode=(*np->info.func)(np);
rCode=(*n2.info.func)(np);
return(0);
}