gpt4 book ai didi

c - 我想在c中实现单独的链接哈希。但 createhashtable 函数中的代码内存不足

转载 作者:行者123 更新时间:2023-11-30 15:31:36 25 4
gpt4 key购买 nike

#include<stdio.h>
#include<stdlib.h>
#define LOADFACTOR 5


struct listnode
{
int key;
int data;
struct listnode *next;
};


struct hashnode
{
int bcount; //block count
struct listnode *next;
};

struct hashtable
{
int size;
int count;
struct hashnode **table;
};

struct hashtable * createhashtable(int s)
{

struct hashtable * h = (struct hashtable*)malloc(sizeof(struct hashtable));
//if(!h)
//retur

h->size = s/LOADFACTOR;
h->count = 0;
h->table = (struct hashnode **)malloc(sizeof(struct hashnode *) * (h->size));
if(!h->table)
printf("memory erroe");
int i;
for(i=0;i< h->size;i++)
{
printf("a");
h->table[i]->next = NULL;
h->table[i]->bcount =0; giving error in this for loop
}
return h;
}
int hash(int size , int item)
{
int index = item %size;
return index;
}

int hashsearch(struct hashtable * h , int item)
{
struct listnode *temp = NULL;

temp = h->table[hash(h->size,item)]->next;
while(temp)
{
if(temp->data == item)
return 1;
temp = temp->next;
}
return 0;
}

int insertintohash(struct hashtable *h , int item)
{
int index;
struct listnode * newnode ,*temp;

if(hashsearch(h,item))
return 0;

index = hash(h->size,item);
temp = h->table[index]->next;
newnode = (struct listnode *)malloc(sizeof(struct listnode));
if(!newnode)
{
printf("out of space");
return -1;
}
newnode->key = index;
newnode->data = item;
newnode->next = h->table[index]->next;
h->table[index]->next = newnode;
h->table[index]->bcount++;
h->count++;
return 1;
}


int main()
{

struct hashtable * h = NULL;
h = createhashtable(60);

if(insertintohash(h,5))
printf("successfully inserted");
return 0;



}

createhashtable 函数在将每个哈希表节点下一个指针分配为 NULL 时给出运行时错误

createhashtable 中使用的 for 循环给出了运行时错误,请给我一个解决方案

最佳答案

h->table 是指向struct hashnode 的指针。您分配了一个12 个指向struct hashnode 的指针的列表。这些指针不是已初始化。您需要首先在循环内执行此操作:

h->table[i] = malloc(sizeof(struct hashnode));

当然,要进行适当的错误检查。

关于c - 我想在c中实现单独的链接哈希。但 createhashtable 函数中的代码内存不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24670216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com