【发布时间】:2018-01-30 17:08:16
【问题描述】:
任何指导将不胜感激。我个人认为问题出在加载方法上。此外,每个方法的基本功能都写在 cmets 中。我的分段错误可能是什么原因?一切都按预期工作吗?感谢您的宝贵时间。
任何可能指向我正确方向的资源也将不胜感激。
/**
* Implements a dictionary's functionality.
*/
#include <stdbool.h>
#include "dictionary.h"
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <cs50.h>
//Defining node:
typedef struct node
{ //Inner workings of each "element" in the linked lists
char word[LENGTH + 1]; //the word within the node is +1'd due to the memory after the word containing /0
struct node *next; //linked list
}node;
node *alphabetList[27]; //26 buckets that can contain variables of type node(of dynamic size)
//one bucket for each letter of the alphabet
node *cursor = NULL;
node *head = NULL;
/**
* Returns true if word is in dictionary else false.
*/
bool check(const char *word)
{
int bucketIndex ;
//no need to malloc information b/c we are simply pointing to previously established nodes.
if(word[0] >= 65 && word[0] < 97){
bucketIndex = word[0] - 65;
}
else{
bucketIndex = word[0] - 97;
}
node *head = alphabetList[bucketIndex];
node *cursor = head;
while(cursor != NULL)
{
cursor = cursor -> next;
if(strcmp(cursor -> word, word) != 0)
{
return true;
}
}
return false;
}
/**
* Loads dictionary into memory. Returns true if successful else false.
*/
bool load(const char *dictionary)
{
char *word = NULL;
int i = 0; //index
FILE *dictionaryTextFile;
dictionaryTextFile = fopen(dictionary, "r");
//scan for word
while(fscanf(dictionaryTextFile, "%s", word) != EOF)
{
//for every word we scan we want to malloc a node to ascertain we have sufficent memory
node *new_node = malloc(sizeof(node));
if(new_node == NULL) //error check(if you run out of memory malloc will return null)
{
unload();
return false;
}
//error check complete.
else{
strcpy(new_node -> word, word);
}
//not sure from here on
char first_letter = new_node[i].word[0]; //first letter of node word (confused on how to execute this properly)
first_letter = tolower(first_letter);
int index = first_letter - 97;
if(word){
for(node *ptr = alphabetList[index]; ptr!= NULL; ptr = ptr->next)
{
if(!ptr-> next){
ptr->next = new_node;
}
}
}
else
{
alphabetList[index] = new_node;
}
i++;
}
return true;
}
/**
* Returns number of words in dictionary if loaded else 0 if not yet loaded.
*/
unsigned int size(void)
{
return 0;
}
/**
* Unloads dictionary from memory. Returns true if successful else false.
*/
bool unload(void)
{
for(int i = 0; i <= 26; i++)
{
node *head = alphabetList[i];
node *cursor = head;
while(cursor != NULL)
{
node *temp = cursor;
cursor = cursor -> next;
free(temp);
}
}
return true;
}
【问题讨论】:
-
您遇到了什么问题?
load功能不起作用吗?它目前没有做的事情是什么意思?根据提供的有限信息,它看起来应该做你想做的事。 -
很抱歉最初的措辞不正确。基本上,加载方法必须从字典文件中获取信息,然后允许程序的其余部分使用它。我也遇到了分段错误,我不确定它应该在哪里。我想知道使用 [i] 遍历节点是否也会达到我想要的结论
-
在调试器(即 gdb)中运行您的代码。它会告诉你分段错误发生在哪里。这是您需要添加到问题中的重要信息
-
当我在 cloud9 上的 cs50 调试器中运行它时,它告诉我我的问题从第 70 行开始(while 循环的开始)。非常感谢您的宝贵时间。
-
另外,我的for循环写得好吗?我一直偏执,这是我的另一个错误。对不起,这是我第一次被困在一个程序上,我有点疯了
标签: c list pointers nodes cs50