单词表及其函数

#define MAXKEY 1024                 //哈希表容量
TkWord *tk_hashtable[MAXKEY];       //单词哈希表
DynArray tktable;                   //单词表
typedef struct TkWord
{
    int tkcode;                     //单词编码
    struct TkWord *next;            //指向哈希冲突的同义词
    char *spelling ;                //单词字符串
    struct Symbol *sym_struct;      //指向单词所表示的结构定义
    struct Symbol *sym_identifier;  //指向单词所表示的标识符
}TkWord;

TkWord *tkword_direct_insert(TkWord *tp)/**功能:运算符,关键字,常量直接放入单词表**/
{
    int keyno;
    dynarray_add(&tktable,tp);          /**把tp插入单词表**/
    keyno=elf_hash(tp->spelling);       /**找到tp在哈希表中位置然后逆序插入**/
    tp->next=tk_hashtable[keyno];
    tk_hashtable[keyno]=tp;
    return tp;
}
TkWord *tkword_find(char *p,int keyno)/**在单词表中查找单词,p是要查找的单词,keyno是单词哈希值**/
{
    TkWord *tp=NULL,*tp1;
    for(tp1=tk_hashtable[keyno];tp1;tp1=tp1->next)
    {
        if(!strcmp(tp1->spelling,p))
        {
            token=tp1->tkcode;      /**token是一个全局变量,记录单词的编码值,但现在这还没定义,了解就行**/
            tp=tp1;
        }
    }
    return tp;                       /**找到了就返回找到的值,没找到就返回它的初值NULL**/
}
TkWord *tkword_insert(char *p)      /**功能:标识符插入单词表,先查找,查找不到再插入单词表**/
{
    TkWord *tp;
    int keyno;
    char *s;
    char *end;
    int length;
    keyno=elf_hash(p);
    tp=tkword_find(p,keyno);
    if(tp==NULL)
    {
        length=strlen(p);
        tp=(TkWord*)malloc(sizeof(TkWord)+length+1);
        tp->next=tk_hashtable[keyno];
        tk_hashtable[keyno]=tp;
        dynarray_add(&tktable,tp);
        tp->tkcode=tktable.count-1;
        s=(char *)tp+sizeof(TkWord);
        /**tp是已经分配空间的一个指针,空间包含sizeof(TkWord)+length+1
        先把tp强制转换成字符指针的形式,再加sizeof(TkWord),刚好把指针移到
        指向tp->spelling的地址**/
        tp->spelling=(char *)s;
        for(end=p+length;p<end;)
        {
            *s++=*p++;
        }
        *s=(char)'\0';
    }
    return tp;
}
void *mallocz(int size)         /**分配内存并把数据初始化为'0'**/
{
    void *ptr;
    ptr=malloc(size);
    if(!ptr&&size)              /**size是分配内存大小**/
        error("内存分配失败");
    memset(ptr,0,size);         /**填充'0'**/
    return ptr;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值