哈希表(封闭寻址).如何初始化和打印
hash tables (Closed addressing). How to initialize and print?
对于封闭寻址,我应该如何处理哈希表?
数据结构:
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变量是个坏主意。
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 在C++中初始化和打印 2D 数组
- 为什么调用 cout.operator<<(const char*) 打印地址而不是字符串? 如何创建一个函数本地静态"HashSet<char>"并初始化它一次?
- 字符串初始化和打印
- 为什么通过添加字符串文字和char初始化时,为什么不打印字符串
- 神秘错误;C 类的私有变量即使在初始化后也不会打印其值
- 访问和打印用 new 初始化的矢量的矢量
- 当我在C 中打印一个非初始化的变量时会发生什么
- 初始化结构/类中的向量并打印出来
- 为什么未初始化的变量打印一个奇怪的负值
- 用"*"(特殊字符)初始化向量,然后打印出来
- 当一个变量打印未初始化的变量contain时,在C++中该怎么办
- 哈希表(封闭寻址).如何初始化和打印
- (C++)使用指向整数的顺从指针初始化字符串变量并且它正在打印某些内容?
- 初始化字符串指针数组,并通过函数调用将其打印出来
- 初始化数组工作得很好,但是当试图将其打印出来时,它会打印出一个额外的列和一个意外字符