首页 > 解决方案 > 为什么在尝试比较字符数组时会出现分段错误?

问题描述

我对 C 非常陌生,正在尝试确定“单词”出现在“句子”中的次数,但是当我尝试运行它时,我一直遇到分段错误。但是,当我在循环中删除 if 语句时,它运行得很好。为什么是这样?

 90 int word_freq(char *sentence, char *word){
 91         int n = 0;
 92         int max_size = strlen(word);
 93         char *token;
 94         printf("chosen word: %s\nmax size: %d\n", word, max_size);
 95         token = strtok(sentence, " "); // first token
 96         
 97
 98         if (strncmp(token, word, max_size) == 0) {
 99             n++;
100         }
101         
102         while (token != NULL) {
103             printf("%s", "x");
104             token = strtok(NULL, " ");
105             if (strncmp(token, word, max_size) == 0) {
106                 n++;
107             }
108         }
109         
110         printf("\n");
111         return n;
112 }

标签: cstrtok

解决方案


第二个在您测试它是否是之前strncmp进行比较。token NULL

只需重新排序逻辑流程 - 您只需要该行一次,就像这样

token = strtok(sentence, " ");      // first token
while (token != NULL) {
    printf("%s", "x");
    if (strncmp(token, word, max_size) == 0) {
        n++;
    }
    token = strtok(NULL, " ");      // next token
}

推荐阅读