Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 在strstr中检查字符指针是否为NULL_C_Strstr - Fatal编程技术网

C 在strstr中检查字符指针是否为NULL

C 在strstr中检查字符指针是否为NULL,c,strstr,C,Strstr,我试图在C中实现strstr 但是我被这段代码卡住了,它在运行时崩溃了 while (*a==*b && a != NULL && b != NULL) { a++ b++ } if (b == NULL || *b == '\0') { // string found } 在谷歌搜索了一段时间后,我发现了这个错误 我应该让我的循环执行以下操作: while (*a==*b && *a != 0 && *b !=

我试图在C中实现strstr 但是我被这段代码卡住了,它在运行时崩溃了

while (*a==*b && a != NULL && b != NULL) {
    a++
    b++
}
if (b == NULL || *b == '\0') { // string found }
在谷歌搜索了一段时间后,我发现了这个错误

我应该让我的循环执行以下操作:

while (*a==*b && *a != 0 && *b != 0) {
    a++
    b++
}
if (*b === 0) { // string found }

但是我仍然不清楚为什么第一种方法不起作用?

您必须遵从指针来比较它的值。

区别在于
a!=NULL与
*a!=0

回想一下,字符串是一个字符数组,最多包含终止的空字符
'\0'
。代码通常传递指向第一个字符的指针,而不是传递字符串

a!=NULL
测试指针是否等于NULL
。值为
NULL
的指针永远不是字符串。它只是指向一个永远不会有任何有效数据的位置的指针

*a!=0
测试指针
a
(假设它是
char*
类型)是否指向一个
char
字符,该字符的值不为空字符
'\0'
,因为这将是字符串的结尾。因此,循环应该停止


注:循环可以简化。当代码到达
*b!=0
,它已经不能有
“\0”的值

// while (*a==*b && *a != 0 && *b != 0) {
while (*a==*b && *a != 0) {
    a++
    b++
}
// if (*b === 0) { // string found }  Type use ==, not ===
if (*b == 0) { // string found }