【发布时间】:2019-04-19 00:47:57
【问题描述】:
我是 C 编程新手。我正在尝试在 CS50 中执行 pset5,同时尝试理解内存、链表和哈希表的概念。我编写了代码并编译了它,但似乎有问题,因为每次我尝试执行代码时它都会返回一些垃圾值。有人可以帮我吗?非常感谢。
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#include "dictionary.h"
#define DICTIONARY "dictionaries/small"
typedef struct node
{
char WORD[LENGTH + 1];
struct node *next;
}
node;
int hash(char *word);
int main(void)
{
node **HASHTABLE = malloc(sizeof(node) * 26);
//open the dictionary
FILE *dic = fopen(DICTIONARY, "r");
if (dic == NULL)
{
fprintf(stderr, "Could not open the library\n");
return 1;
}
int index = 0;
char word[LENGTH + 1];
for (int c = fgetc(dic); c != EOF; c = fgetc(dic))
{
word[index] = c;
index++;
if (c == '\n')
{
int table = hash(word);
printf("%d\n", table);
//create a newnode
node *newnode = malloc(sizeof(node));
strcpy(newnode->WORD, word);
newnode->next = NULL;
printf("Node: %s\n", newnode->WORD);
index = 0;
//add new node to hash table
if (HASHTABLE[table] == NULL)
{
HASHTABLE[table] = newnode;
}
else
{
HASHTABLE[table]->next = newnode;
}
}
}
for(int i = 0; i < 26; i++)
{
node *p = HASHTABLE[i];
while (p != NULL)
{
printf("%s", p->WORD);
p = p->next;
}
}
//free memory
for(int i = 0; i < 26; i++)
{
node *p = HASHTABLE[i];
while (p != NULL)
{
node *temp = p->next;
free(p);
p = temp;
}
}
free(HASHTABLE);
}
int hash(char *word)
{
int i = 0;
if (islower(word[0]))
return i = word[0] - 'a';
if (isupper(word[0]))
return i = word[0] - 'A';
return 0;
}
【问题讨论】:
-
for (int c = fgetc(dic); c != EOF; c = fgetc(dic))通常写成int c; while ((c = fgetc(dic)) != EOF) -
顺便说一句,您应该将输出包含为代码块,而不是图像...
-
另一个问题是尝试添加 3 个具有相同首字母的单词 - 您的哈希表链接不正确。
-
@AnttiHaapala 非常感谢您的 cmets。他们非常有帮助!这是我的第一个问题,所以我很难包含一个代码,也对图像感到抱歉。而且我并没有真正得到您对具有相同首字母的 3 个单词的评论……我只是在尝试使用试用词典。
标签: c memory linked-list hashtable cs50