【发布时间】:2019-03-25 12:24:36
【问题描述】:
我需要编写在哈希表中加载字典的函数。我对错误消息感到困惑:c:37:20 运行时错误:加载类型为“const char”的空指针,在分段错误中运行。
我尝试改变加载功能,但仍然没有帮助。并且还尝试为哈希表分配内存,因为我认为问题可能在于内存泄漏。
` // Represents number of buckets in a hash table
#define N 26
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Represents a hash table
node *hashtable[N];
// Hashes word to a number between 0 and 25, inclusive, based on its first letter
unsigned int hash(const char *word)
{
// Allocates memory for hashtable
int *ht = malloc(26*sizeof(int));
if(!ht)
{
unload();
return false;
}
return tolower(word[0]) - 'a'; // this is error line 37:20
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
// Initialize hash table
for (int i = 0; i < N; i++)
{
hashtable[i] = NULL;
}
// Open dictionary
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
unload();
return false;
}
// Buffer for a word
char word[LENGTH + 1];
// Insert words into hash table
while (fscanf(file, "%s", word) != EOF)
{
for (int i = 0; i < N; i++ )
{
// Allocate memory for node for each new word
node *new_node = malloc(sizeof(node));
if (!new_node)
{
unload();
return false;
}
// Copies word into node
strcpy(new_node->word, word);
new_node->next = NULL;
// Hashes word
hash(new_node->word);
// Inserts word into linked list
if(hashtable[i] == 0)
{
hashtable[i] = new_node;
}
else if(hashtable[i] == new_node)
{
new_node->next = hashtable[i];
hashtable[i] = new_node;
}
}
}
// Close dictionary
fclose(file);
// Indicate success
return true;
}
加载字典时,函数 load 应该返回 true。但我得到分段错误。这是否意味着我没有从加载函数中得到正确的输出?
【问题讨论】:
-
缺少的东西:第 37 行是哪一行?
-
对不起,如果我的问题有任何错误。我是第一次使用堆栈))))你可以在代码中看到它 return tolower(word[0]) - 'a'; // 这是错误行 37:20
-
另外,有问题的代码不是minimal reproducible example - 例如
node的定义是什么 -
另外
hash返回一个值,您可能希望将其存储在变量中并稍后使用,但我没有看到任何证据 - 而是丢弃返回值并稍后使用i。 -
这是结构节点和哈希表的定义 // 表示哈希表中的桶数 #define N 26 也许我 malloc memoryfor hashtable 的方式错误? // 表示哈希表中的一个节点 typedef struct node { char word[LENGTH + 1];结构节点*下一个; } 节点; // 表示一个哈希表节点 *hashtable[N];
标签: c