2017-10-13 76 views
-1
我有在pset5一些麻煩

負荷的,其實我不知道如何開始調試,我看過的教訓了幾次,現在我不會在任何地方得到..Pset5實現使用特里

當我運行speller.c它給我一個賽格故障,我跑調試器,它崩潰的For循環的beggining,這裏如下我的代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <stdbool.h> 
#include <ctype.h> 
#include <string.h> 

#include "dictionary.h" 
// default dictionary 
#define DICTIONARY "dictionaries/large" 

//created the struct node 
typedef struct node 
{ 
    bool is_word; 
    struct node * paths[27]; 
} 
node; 

int letter = 0; 
char * word = NULL; 

/** 
* Returns true if word is in dictionary else false. 
*/ 
bool check(const char *word) 
{ 
//todo 
return false; 
} 

/** 
* Loads dictionary into memory. Returns true if successful else false. 
*/ 
bool load(const char *dictionary) 
{ 
//opens dictionary for reading 
FILE *fp = fopen(DICTIONARY, "r"); 
if (fp == NULL) 
{ 
    return false; 
    unload(); 
} 

//creates the root of the trie 
node *root = malloc(sizeof(node)); 
root -> is_word = false; 

node * trav = root; 

char * word = NULL; 

//start reading the file 
while (fscanf(fp, "%s", word) != EOF) 
{ 
    for (int i = 0; i < strlen(word); i++) 
    { 
     //assing wich path to take 
     char c = fgetc(fp); 
     if (isupper(c)) 
     { 
      letter = tolower (c); 
      letter = letter -'a'; 
     } 
     else if (isalpha(c)) 
     { 
      letter = c; 
      letter = letter -'a'; 
     } 
     else if (c == '\'') 
     { 
      letter = 26; 
     } 
     else if (c == '\0') 
     { 
      trav -> is_word = true; 
     } 
     if (trav -> paths[letter] == NULL) 
     { 
      node *new_node = malloc(sizeof(node)); 
      if (new_node == NULL) 
      { 
       return false; 
       unload(); 
      } 
      //point to new node 
      trav -> paths[letter] = new_node; 
     } 
     else 
     { 
      trav = trav -> paths[letter]; 
     } 
    } 

} 
if (fscanf(fp, "%s", word) == EOF) 
{ 
    fclose(fp); 
    return true; 
} 
return false; 
} 

/** 
* Returns number of words in dictionary if loaded else 0 if not yet loaded. 
*/ 
unsigned int size(void) 
{ 
// TODO 
return 0; 
} 

/** 
* Unloads dictionary from memory. Returns true if successful else false. 
*/ 
bool unload(void) 
{ 
// TODO 
return false; 
} 

我也不知道如何將new_node指向下一個新節點,以及我是否必須爲它們指定不同的名稱。例如,我要存儲單詞「foo」的,所以我讀叫TRAV節點,進入路徑[5](在F字母),檢查它是否已經打開,如果不是(如果它是NULL)我創建了一個名爲new_node和點TRAV節點 - >路徑[5]吧,比我應該更新TRAV成爲新的節點,所以其指向它自己的路[信]

+0

與您的問題無關,但您確實知道'return'立即返回*?在return之後的同一個作用域中的任何代碼都不會被執行,這就是所謂的*死代碼*。如果你無法打開文件,在'load'函數中你有* dead code *。 –

+0

至於你的問題,當你把它傳遞給'fscanf'時,'word'指向哪裏? 'fscanf'不會爲你分配內存。 –

+0

對不起,我更新了代碼指向單詞,只是忘了發佈在這裏:char * word = NULL; –

回答

-1

wordNULL指針。並且fscanf沒有(不能真的)爲該指針分配內存來指向。當fscanf要提領word寫它讀取字符會發生什麼?你不能取消引用NULL指針,它會導致未定義的行爲。我建議你將單詞定義爲一個數組。

注:取自評論的答案