【发布时间】:2015-03-02 10:56:14
【问题描述】:
我不知道我的问题是内存泄漏,还是我没有以正确的方式访问哈希表。
我的哈希.h
#define HASHSIZE 31
#define EMPTY ""
#define DELETED "-"
typedef char KeyType[9];
typedef void *Info;
typedef struct entry
{
KeyType key;
Info info;
}Entry;
typedef Entry HashTable[HASHSIZE];
我的 hash.c
int Hash(KeyType k){
return atoi(k)%HASHSIZE;
}
void InitializeTable(HashTable t){
for(int i=0; i < HASHSIZE; i++){
strncpy(t[i].key,EMPTY,9);
}
}
void ClearTable(HashTable t){
InitializeTable(t);
}
void InsertTable_LP(HashTable t, KeyType k, Info i){
int a = 0;
int hash = Hash(k);
while((a<HASHSIZE)
&& strcmp(t[hash].key,EMPTY)!=0
&& strcmp(t[hash].key,DELETED)!=0 ){
hash = (hash + 1) % HASHSIZE;
a++;
}
strncpy(t[hash].key,k,9);
t[hash].info = i;
printf("Value of info is %d\n",(int)t[hash].info);
}
int RetrieveTable_LP(HashTable t, KeyType k){
int a=0;
int hash = Hash(k);
while(a<HASHSIZE
&& strcmp(t[hash].key,k)!=0
&& strcmp(t[hash].key,EMPTY)!=0){
hash=(hash+1) % HASHSIZE;
a++;
}
if(strcmp(t[hash].key,k)==0)
return hash;
return -1;
}
int main(){
HashTable *t = malloc(HASHSIZE*sizeof(Entry));
int valores[] = {1,2,3,4,5,6,7,8,9};
ClearTable(*t);
InsertTable_LP(*t,"1",valores);
InsertTable_LP(*t,"2",valores+1);
InsertTable_LP(*t,"3",valores+2);
InsertTable_LP(*t,"4",valores+3);
InsertTable_LP(*t,"5",valores+4);
int pos = RetrieveTable_LP(*t,"2");
if(pos==-1){
printf("Error\n");
}
else
printf("Position %d\n",pos);
printf("okay %d\n",(int)t[pos]->info);
printf("asdasdas\n");
return 1;
}
我的输出是
Value of info is 1537727040
Value of info is 1537727044
Value of info is 1537727048
Value of info is 1537727052
Value of info is 1537727056
Position 2
okay 0
如果有人能给我解释一下,在此先感谢。
【问题讨论】:
-
看看你的代码,我发现
(int)t[hash].info是完全错误的:你将Info转换为void*到int -
将此作为练习,而不是我自己的实现。即便如此,如果我没记错的话 void* 让我得到任何类型的变量,因为我输入了一个 int 作为信息,我可以将它转换为 int。
-
你的意思是取消引用它!不是很明显它会是
*(int*)而不是(int)!祝你好运! -
谢谢@Meninx!但是如果我这样做,我会遇到分段错误,但正如@iharob 所说,问题可能出在插入函数上!这就是为什么在进来之前,我在进来之前尝试了函数内部的printf。
-
希望您解决了您的问题! :)
标签: c algorithm hash hashtable