[英]CS50 pset5 Load Function
我在CS50上的pset5的加載部分遇到了一些麻煩,如果有人可以提供幫助,那就太好了。 我正在嘗試加載從字典(下面的文件fp)中讀取的特里,然后遍歷字母以創建特里。
我了解構建特里的概念,但是我認為我在結構指針的設置方面缺少一些東西(希望我不會在下面的代碼中走得很遠)。 我嘗試設置“陷阱”以瀏覽嘗試的每個階段。
我目前遇到細分錯誤,因此無法完全確定下一步該怎么做。 任何幫助將不勝感激。
/**
* Loads dictionary into memory. Returns true if successful else false.
*/
bool load(const char* dictionary)
{
//create word node and set root
typedef struct node {
bool is_word;
struct node* children[27];
} node;
node* root = calloc(1, sizeof(root));
root -> is_word = false;
node* trav = root;
//open small dictionary
FILE* fp = fopen(dictionary, "r");
if (fp == NULL)
{
printf("Could not open %s.\n", dictionary);
return false;
}
//read characters one by one and write them to the trie
for (int c = fgetc(fp); c != EOF; c = fgetc(fp))
{
//set index using to lower. Use a-1 to set ' to 0 and other letters 1-27
int index = tolower(c)-('a'-1);
//if new line (so end of word) set is_word to true and return trav to root)
if (index == '\n')
{
trav->is_word = true;
trav = root;
}
//if trav-> children is NULL then create a new node assign to next
//and move trav to that position
if (trav->children[index] == NULL)
{
node* next = calloc(1, sizeof(node));
trav->children[index] = next;
trav = next;
}
//else pointer must exist so move trav straight on
else {
trav = trav->children[index];
}
}
fclose(fp);
return false;
}
我假設您將數組children[]
的大小設置為存儲26個字母和撇號。 如果是這樣,則當fgetc(fp)
返回帶有acsii代碼39的撇號(我認為)時, index
將設置為-57,這絕對不是trav->children
一部分。 那可能就是您遇到段錯誤(或至少其中一個地方)的地方。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.