我必须使用下面的结构在 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: %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);
}
关于c - 使用回调和嵌套列表的 C 前缀表达式计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23037566/