如果我将 p!=nullptr 更改为 *p!='\0',那么它可以工作,但为什么呢?

If I change p!=nullptr into *p!='', then it works, but why?

本文关键字:工作 为什么呢 如果 nullptr      更新时间:2023-10-16

My IDE is Xcode.以下代码无法按预期运行。尽管在较新的C++标准中建议使用nullptr。

#include<iostream>
using namespace std;
int count_x(char * p, char x)
{
    if(p==nullptr)return 0;
    int count = 0;
    for (; p!=nullptr; ++p)
        if(*p == x)
            ++count;
    return count;
}
int main()
{
    char str[] = "I'm a little girl in the little world!";
    cout<<"number of t in the string is "<<count_x(str, 't')<<"n";
}
/*
 the expected output is:
 number of t in the string is 5
 Program ended with exit code: 0
*/

上面的代码可以成功编译,但是当我运行它时,我无法获得预期的输出。在调试模式下,我发现 for 循环没有停止。所以我将代码更改为以下代码:

#include<iostream>
using namespace std;
int count_x(char * p, char x)
{
    if(p==nullptr)return 0;
    int count = 0;
    for (; *p!=''; ++p)
        if(*p == x)
            ++count;
    return count;
}
int main()
{
    char str[] = "I'm a little girl in the little world!";
    cout<<"number of t in the string is "<<count_x(str, 't')<<"n";
}
/*
 the expected output is:
 number of t in the string is 5
 Program ended with exit code: 0
*/

在我将 p!=nullptr 更改为 *p!='\0' 后,代码工作正常,并且得到了预期的输出。虽然代码似乎有效,但我仍然不明白失败或成功的原因。

你能给我一些线索或建议吗?谢谢。

唯一的区别是将 nullptr 更改为"\0"。

还有另一个区别:

 p!=nullptr
*p!=''
^
|
+---- right here, a dereference operation
<小时 />

我仍然不明白失败的原因...

我发现 for 循环并没有停止

您的条件是在 p 的值为 nullptr(即零(时停止。但是你只增加p,所以它怎么可能达到零?在你飞过字符串之前,它永远不会达到零。

我仍然不明白原因...成功。

在成功的尝试中,结束条件不是比较指针,而是将指向的值与 null 终止字符进行比较。只要字符串以 null 结尾,这就可以工作。

<小时 />

附加说明:即使空指针和空字符具有相同的名称 (null( 和相同的值 (0(,它们具有不同的类型并且是不同的概念。

nullptr类型是std::nullptr_t 。它是可以转换为任何类型的
通用指针文本''的类型是char。它用于C样式字符串中,用于标记字符串终止。
两者在您的平台上可能是相同的值,但类型不同。例如,将 0 公里与 0 公斤进行比较是不好的。


现在你的代码中真正的问题是p == nullptr .你不能指望指针通过递增而变得nullptr(开始指向任何内容(。

唯一的区别是将nullptr更改为''

不,您还将p更改为*p.

考虑

int test = NULL;

int *test = NULL;

上面的两个代码都可以工作。(尽管上面的第一行会说一些关于"从 NULL 转换为非指针类型"的警告

然而

nullptr 实际上是一个"空指针",并且始终是一个指针。如果尝试将其分配给整数。它会导致错误

int test = nullptr;

但如果它是

int *test = nullptr;