c - c编程函数不返回false
问题描述
#include "ctype.h"
#include "string.h"
#include "stdbool.h"
#include "stdio.h"
int check_for_sub_string(char s[],char word[])
{
int flag = false;
char mark[]=" ";
char *tok;
tok = strtok(s,mark);
while (tok!=NULL)
{
tok= strtok(NULL,mark);
if (strcmp(tok,word)==0)
{
flag= true;
return flag;
}
else flag = false;
}return flag;
}
据说,当我使用不在字符串中的单词运行代码时,它不会返回 0。我不知道为什么。例如,我使用 s[]="this is a test string" 和 word[]="kol" 运行它,它不会返回 0。我将返回标志放在循环的末尾,所以如果它没有'找不到返回false的词。
解决方案
它不会返回 false 因为它崩溃(或至少调用未定义的行为):当您到达字符串的末尾时,strtok
返回 NULL,但您立即将该 NULL 指针传递给strcmp
. 直到循环体结束时才进行测试tok != NULL
,那为时已晚。
推荐阅读
- c# - 从 Windows 窗体套接字应用程序向 UWP 套接字应用程序发送消息
- python - 无法获取代码来检索 Input() 的指数,并确定它是数字还是字母以输出正确的注释
- php - 我应该在哪里放置我想在多个控制器中使用的功能,而不仅仅是在我创建它的控制器中?
- javascript - 如何在没有 HTML 的 JavaScript (nodejs) 中创建一个函数来接收键盘输入
- swift - Firestore 查询 geohash 过滤
- python-3.x - sys.excepthook 不返回异常
- javascript - JINT 转换字典
转 JSON 字符串 - google-sheets - 基于索引和匹配变量的动态下拉列表
- r - R:处理表情符号并将其转换为规范形式
- regex - 用于匹配 3 个字母和 1-2 位数字的正则表达式