哈希表(封闭寻址).如何初始化和打印

hash tables (Closed addressing). How to initialize and print?

本文关键字:初始化 打印 寻址 哈希表      更新时间:2023-10-16

对于封闭寻址,我应该如何处理哈希表?

数据结构:

typedef char ktype[9];
typedef void *Infoc;
typedef struct entryc{
    ktype ckey;
    Infoc infoc;
    struct entryc *next;
} Entryc;
typedef Entryc *Chashtable[HASHSIZE];

我正在声明一个结构数组的指针,已初始化:

void initChain(Chashtable *h){
    int i;
    for(i=0; i<HASHSIZE; i++){
        *h[i] = NULL;
    }
}

这是插入代码:

void insertChain(Chashtable *h, ktype k, Infoc inf){
    int n= hash(k, 0);
    char hkey[3];
    sprintf(hkey, "%d", n);
    struct entryc *new = malloc (sizeof(struct entryc));
    strcpy(new->ckey, hkey);
    new->infoc = inf;
    new->next = *h[n];
    *h[n] = new;
}

我想打印出哈希表:

void printChain(Chashtable *h){
    int i;
    for(i=0; i<HASHSIZE; i++){
        if((*h[i])){
        printf("-> %sn", (*h[i])->ckey);
        }
    }
}

打印时出现分段错误,为什么?

谢谢。

编辑:

带有分段错误的完整代码(在调试器中未发现其他错误):

**

完整的可编译代码在这里:

**http://pastebin.com/GHpfqmP3

对于函数参数和实现,您的指针都错了。CCD_ 1是CCD_ 2指针的数组。我在所有地方都删除了一个间接级别,代码现在运行了,也许不是你想要的!顺便说一句,我不得不修补一个hash()函数。我希望你能从这里开始。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define HASHSIZE 31
#define EMPTY   " "
#define DELETED "-"
typedef char ktype[9];
typedef void *Infoc;
typedef struct entryc{
    ktype ckey;
    Infoc infoc;
    struct entryc *next;
} Entryc;
typedef Entryc *Chashtable[HASHSIZE];
int hash(ktype k, int z) {
   return rand() % HASHSIZE;
}
void initChain(Chashtable h){
    int i;
    for(i=0; i<HASHSIZE; i++){
        h[i] = NULL;
    }
}
void printChain(Chashtable h){
    int i;
    for(i=0; i<HASHSIZE; i++){
        if((h[i])){
        printf("-> %sn", (h[i])->ckey);
        }
    }
}
void insertChain(Chashtable h, ktype k, Infoc inf){
    int n= hash(k, 0);
    char hkey[3];
    sprintf(hkey, "%d", n);
    struct entryc *new = malloc (sizeof(struct entryc));
    strcpy(new->ckey, hkey);
    new->infoc = inf;
    new->next = h[n];
    h[n] = new;
}
int main(void) {
    // system ("tput clear");
    Chashtable j;
    initChain(j);
    printChain(j);
    insertChain(j, "myname", "single");
    printChain(j);
    return 0;
}

我认为您既想分配(在初始化中)h[i]的值,又想检查(在打印中)*h[i]的值。

作为一个侧面,你的插件看起来也有斑点。如果没有别的,几乎所有的C编译器都是C++编译器,new是C++关键字。所以用这个名字来命名C变量是个坏主意。