【发布时间】:2011-06-21 02:06:48
【问题描述】:
我正在尝试将一个项目添加到我的 Hashtable 中,我已经使用了很多 printf 来看看发生了什么,但它看起来应该添加它,但实际上不是。
这是我的代码:
struct hashnode_s {
char *key;
ValueType tag;
union
{
int IntegerValue;
char *StringValue;
}u;
struct hashnode_s *next;
};
我正在尝试模仿 GCC 编译器。 用我的哈希表
typedef struct hashtbl {
hash_size size;
struct hashnode_s **nodes;
hash_size (*hashfunc)(const char *);
} HASHTBL;
和我的插入方法
int hashtbl_InsertString(HASHTBL *hashtbl, const char *key, const char *value)
{
struct hashnode_s *node;
hash_size hash;
hash = SearchForHashIndex(hashtbl, key, value);
if(hash ==-1)
{
hash=hashtbl->hashfunc(key);
}
fprintf(stderr, "hashtbl_insert() key=%s, hash=%d\n\n\n", key, hash);
node=hashtbl->nodes[hash];
while(node)
{
printf("In while\n\n\n\n\n");
/* This Code isn't correct
if(!strcmp(node->key, key)) {
node->data=data;
return 0;
}*/
node=node->next;
}
if(!(node=malloc(sizeof(struct hashnode_s)))) return -1;
if(!(node->key=mystrdup(key))) {
free(node);
return -1;
}
node->key = key;
node->tag = StringConst;
node->u.StringValue = value;
node->next=hashtbl->nodes[hash];
printf("ADDING HASH NODE \n\n\n");
hashtbl->nodes[hash]=node;
return 0;
}
我在搜索方法时不断得到空值。不应该是这样。我是否正确插入?
int SearchForHashIndex(HASHTBL *hashtbl, const char *key, const char *value)
{
printf("INSIDE SEARCH FOR HASH INDEX \n\n\n\n\n");
int i;
for(i=0; i < CurrentHashSize; i++)
{
struct hashnode_s *node;
node = hashtbl->nodes[i];
printf("%d\n",i);
if(node == NULL)
{
printf("NULL");
}
while(node)
{
if(strcmp(node->key,key) || strcmp(node->u.StringValue,value))
{
printf("INSIDE HERE!\n");
return i;
printf("returning %d\n",i);
}
node = node->next;
}
}
printf("returning -1\n");
return -1;
}
【问题讨论】:
-
首先,你的
printf("returning %d\n", i)永远不会计算,因为它在return语句之后。 -
是的,我注意到了。那是我在那里的东西,我忘了删除大声笑
-
代码的格式是缩进四个空格(也有一个按钮),而不是使用
标签。