【发布时间】:2025-11-03 09:50:01
【问题描述】:
我创建了哈希表来插入我的值。但是当我插入多个值时,我在所有字段中得到了相同的值。我的代码在这里:
为用户和哈希表创建一个结构
struct UserNode
{
char *username;
char *password;
};
struct HashTable
{
int size;
struct UserNode *table;
};
// 将哈希表初始化为NULL
struct HashTable* initializeTable(int size)
{
struct HashTable *htable;
int i = 0;
if (size < MIN_TABLE_SIZE)
{
printf("Table Size Too Small\n");
return NULL;
}
htable = malloc(sizeof(struct HashTable));
if (htable == NULL)
{
printf("Out of Space\n");
return NULL;
}
htable->size = size;
htable->table = malloc(size * sizeof(struct UserNode));
if (htable->table == NULL)
{
printf("Table Size Too Small\n");
return NULL;
}
for (i = 0; i < htable->size; i++)
{
htable->table[i].username= malloc(20 * sizeof(char));
htable->table[i].password = malloc(20 * sizeof(char));
htable->table[i].username=NULL;
htable->table[i].password=NULL;
}
printf("Hsh table sucessfully created\n");
return htable;
}
将每个用户名插入哈希表
int Insert(char *key,char *password,struct HashTable *htable)
{
int pos = 0;
pos = Find(key,htable);
printf("the value of key : %d\n",pos);
if ((htable)->table[pos].username == NULL)
{
(htable)->table[pos].username,key ;
(htable)->table[pos].password = password;
}
else
{
printf("Duplicate element ..\n");
}
return 0;
}
这个函数用来显示哈希表
void Retrieve(struct HashTable *htable)
{
int i=0;
for (i = 0; i < htable->size; i++)
{
if (htable->table[i].username == NULL)
printf("Position: %d \tusername : NULL\tpassword: NULL\n",i + 1);
else
printf("Position: %d \t username: %s\tpassword: %s\n",i + 1,htable->table[i].username,htable->table[i].password);
}
}
我从主函数中调用这些函数:
............主要代码............ ................................... 案例一:
printf("Enter size of the Hash Table:\n");
scanf("%d",&size);
htable = initializeTable(size);
break;
case 2:
if (i > htable->size)
{
printf("Table is Full, Rehash the table\n");
continue;
}
printf("Enter the username:\n");
scanf("%s",&username);
printf("Ebter the password:\n");
scanf("%s",&password);
Insert(username,password,htable);
i++;
break;
case 3:
printf("Display\n");
Retrieve(htable);
break;
但是当我通过插入函数在结构中插入更多用户名和密码时,我在两个字段中得到了相同的值。也就是说,新的将覆盖前一个并将两个值都显示为新用户名。为什么 ?我的代码有问题?
【问题讨论】:
-
在
(htable)->table[pos].username,key ;这一行中似乎是一个简单的错字... -
您为
username和password分配内存,然后立即将两者都设置为NULL。分配的内存将丢失。这两个字段最初都应为NULL。 -
使用 strcpy( ) 时出现分段错误,这就是为什么我使用 (htable)->table[pos].username = key;
-
那我如何让我的字符串为 NULL 开头?
-
因为您只是分配指针,所以所有节点将具有相同的
username和password值。这些字段在输入期间保存不同的数据,但最后,它们只包含最后一个输入集。如前所述,使用strcpy,最好与malloc结合使用。 (函数strdup,如果你的系统有它,可以一次性完成。)
标签: c hash structure dynamic-memory-allocation