0

我已经阅读了这篇文章:在 C 中实现字典的快速方法并实现了它。需要说的是,我将安装和查找更改为使用 hashtab 作为参数而不是全局变量,它的作用就像魅力:

struct nlist *install(struct nlist **hashtab,char *name, symbol *dfn);
struct nlist *lookup(struct nlist **hashtab, char *s);

问题是,我需要将哈希复制到一个新的。我首先尝试:


struct nlist **copy_context(struct nlist **hashtab){
    nlist **copy = (nlist**)malloc(sizeof(nlist*)*HASHSIZE);
    struct nlist *np;
    int i = 0;
    for (np = hashtab[i]; i<HASHSIZE ;i++ ){
        debug_log("i vale %i",i);
        if( np != NULL ){
            install(copy,np->name,np->dfn);
        }
    }
    return copy;
}

但我不清楚这些值存储在哪里,也不清楚从哪里开始复制。我在想类似的事情:

struct nlist **copy_context(struct nlist **hashtab){
nlist **copy = (nlist**)malloc(sizeof(nlist*)*HASHSIZE);
i = 0;//this is not correct
or (np = hashtab[i]; np != NULL; np = np->next){
        install(copy,np->name,np->dfn);
    }
return copy;
}

但值得注意的是工作。

4

1 回答 1

0

正如“一些程序员老兄”所说,我需要做两个循环,一个在表本身上,一个在该表索引中的列表上。

struct nlist **copy_context(struct nlist **hashtab){
    nlist **copy = (nlist**)malloc(sizeof(nlist*)*HASHSIZE);
    struct nlist *np;
    for (int i = 0; i<HASHSIZE; i++ ){
        np = hashtab[i];
        while( np )
        {
            install(copy,np->name,np->dfn);
            np = np->next;
        }
    }
    return copy;
}
于 2020-05-04T18:19:29.393 回答