2016-07-24 15 views
-2

私は辞書で単語を検索するための単純なプログラムを作成しています。これはなぜ私にセグメンテーションフォルトを与えるのですか?

なぜ単語が見つからない場合、これがセグメンテーションフォルトを作成しているのか教えてください。

私は今1時間以上これを見つめています。

#include <stdio.h> 
#include <stdbool.h> 

struct entry 
{ 
    char word[15]; 
    char definition[50]; 
}; 

bool equalStrings(const char s1[], const char s2[]); 
int lookup(const struct entry dictionary[], const char search[], const int entries); 

int main(void) 
{ 
    const struct entry dictionary[100] = 
     {{ "aardvark", "a burrowing African mammal"}, 
     { "abyss", "a bottomless pit"}, 
     { "acumen", "mentally sharp; keen"}, 
     { "addle", "to become confused"}, 
     { "aerie", "a high nest"}, 
     { "affix", "to append; attach"}, 
     { "agar", "a jelly made from seaweed"}, 
     { "ahoy", "a nautical call of greeting"}, 
     { "aigrette", "an ornamental cluster of feathers"}, 
     { "ajar", "partially opened"}}; 


    char word[10]; 
    int entries = 10; 
    int entry; 

    printf("Enter word: "); 
    scanf("%14s", word); 
    entry = lookup(dictionary, word, entries); 

    if(entry != -1) 
     printf("%s\n", dictionary[entry].definition); 
    else 
     printf("Sorry, the word %s is not in my dictionary\n", word); 

    return 0; 
} 

bool equalStrings(const char s1[], const char s2[]) 
{ 
    int i = 0; 
    bool areEqual; 

    while(s1[i] == s2[i] && s1[i] != '\0' && s2[i] != '\0') 
    { 
     i++; 
    } 
     if(s1[i] == '\0' && s2[i] == '\0') 
      areEqual = true; 
     else 
      areEqual = false; 

    return areEqual; 
} 

int lookup(const struct entry dictionary[], const char search[], const int entries) 
{ 
    int i; 
    bool equalStrings(const char s1[], const char s2[]); 

    for(i = 0; 1 < entries; i++) 
    { 
     if(equalStrings(search, dictionary[i].word)) 
     { 
      return i; 
     } 
    }  
    return -1; 
} 
+0

あなたの研究/デバッグの努力をこれまでのところ表示してください。まず[Ask]ページをお読みください。 –

+1
+0

なぜ共通のイディオム 'strcmp(s1、s2)== 0'を使うのではなく、' equalStrings'を自分で実装したのですか? –

答えて

2
for(i = 0; 1 < entries; i++) 

entries常に10あるので、プログラムは、このように範囲外のiを取得し、このループを終了することはありません。代わりにfor(i = 0; i < entries; i++)を使用してください。

関連する問題