C语言中的符号表 [英] A Symbol Table in C

查看:451
本文介绍了C语言中的符号表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一种执行模式匹配的静态分析工具.我正在使用 Flex 生成词法分析器,并且编写了代码来管理符号表.我对 C 不太熟悉,所以我决定将符号表实现为线性链表.

I am currently developing a kind of static analysis tool that performs pattern matching. I am using Flex to generate lexical analyzer, and I wrote code to manage the symbol table. I am not very experienced with C, so I decided to implement the symbol table as a linear linked list.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

struct symtab {
   int id;
   char *name;
   int type;
   struct symtab *next;
};

enum types {
   KEYWORD = 1,
   CONSTANT,
   IDENTIFIER,
   OPERATOR,
   DELIMITER,
   WHITESPACE
};

struct symtab *last_entry(struct symtab *start)
{
   struct symtab *p;
   p = start;
   while(p -> next != NULL) {
      p = p -> next;
   }
   return p;
}

void add_entry(char* name, int type, struct symtab *start)
{
   struct symtab *new;
   new = last_entry(start);
   int id;
   if(new == start) {
      new = start;
      id = 0;
   }
   else {
      new = malloc(sizeof(struct symtab));
      id = last_entry(start) -> id;
      last_entry(start) -> next = new;
   }
   new -> id = id + 1;
   new -> name = name;
       new -> type = type;
   new -> next = NULL;
}

struct symtab *find_entry(char* name, struct symtab *start)
{
   struct symtab *p;
   p = start;
   while(p -> next != NULL) {
      if(strcmp(p -> name, name) == 0) {
         return p;
      }
   }
}

但是,当我使用add_entry()添加符号,然后尝试使用find_entry()查找它们时,find_entry()返回null.有人可以帮忙吗?

However, when I use add_entry() to add symbols, and then try to find them with find_entry(), find_entry() returns null. Can someone please assist?

推荐答案

您似乎正在尝试将列表表示为标头对象(开始),后跟列表的实际元素.这是一个好主意,因为它简化了空列表的情况,但是您没有正确的实现方法.

It looks like you're trying to represent the list as a header object (start), followed by the actual elements of the list. This is a good idea since it simplifies the empty-list case, but you've not got the implementation right.

添加时,您需要删除启动last_entry所获得的特殊情况代码.起始节点将永远不会包含符号数据.

When you add, you need to remove the special case code you've got for last_entry being start. The start node will never contain symbol data.

在查找时,必须确保跳过头(开始),因为它不包含符号数据.查找代码中的第二个错误是,当p-> next为NULL时停止搜索(这意味着您永远无法返回列表中的最后一个元素.)当p为NULL时应该停止搜索.

When you lookup, you've got to make sure you skip the head (start) since it doesn't contain symbol data. A second bug in your lookup code is that you stop searching when p->next is NULL (which means you can never return the final element in your list.) You should stop when p is NULL.

当然,您根本不应该使用链表:哈希表将是更好的选择,因为它具有更好的性能和内存效率.

Of course, you shouldn't be using a linked list at all: a hash table would be a better choice since it's got better performance and memory efficiency.

这篇关于C语言中的符号表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆