c - 使用回调和嵌套列表的 C 前缀表达式计算器

标签 c callback linked-list prefix

我必须使用下面的结构在 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/

相关文章:

javascript - 将回调函数传递给 jQuery AJAX 成功函数

java - 链表内存泄漏

c - 链表的空栈

c++ - C++中的结构体是按顺序分配内存的吗?不知何故每次都能得到指针比较的正确答案

javascript - 从node.js中的回调函数获取result.insertId

python - 类 lambda 回调 NameError

c - 警告 : incompatible implicit declaration of built-in function log2

c - 如何调试由于超出可用动态堆而导致的 Emscripten 段错误

C - Xlib - 使用 XGetWindowProperty 作为窗口标题的 BadWindow 错误

c++ - C/C++ 事件驱动监控非子程序的终止