c - 为什么在尝试比较字符数组时会出现分段错误?
问题描述
我对 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
}
推荐阅读
- docker - 使用 docker 的 nginx 配置问题
- git - 如何使用新的远程提交轻松更新分支的日志消息视图?
- r - 如何用 lubridate 求和或平均多个重叠时间间隔?
- java - 如何转换列表
到一个字符串? - java - Rock Paper Scissors 程序无法正常运行的方面
- graphql - 如何使用 prismic graphql api 按链接文档/关系的 uid 过滤?
- javascript - 关闭选项卡/浏览器时如何注销用户?
- jquery - 使用 jQuery 将数据发布到 tibco
- python - Django模板不从模型返回对象列表
- java - 如何使用开始和结束字符验证构建验证正则表达式?