为什么在尝试比较字符数组时会出现分段错误?

Why do I get a segmentation fault when trying to compare character arrays?

我是 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 }

第二个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
}