如何正确使用nullptr?

Won*_*ong 11 c++ nullptr

目前我正在阅读Byarne Stroustrup的"C++之旅".重要的是:关于"指针,数组和引用",他举了一个关于如下使用的例子nullptr:

int count_x(char* p, char x)
// count the number of occurrences of x in p[]
// p is assumed to point to a zero-terminated array of char (or to nothing)
{

    if (p == nullptr) return 0;
        int count = 0;

    for (; p != nullptr; ++p)
        if (*p == x)
            ++count;

    return count;
}
Run Code Online (Sandbox Code Playgroud)

在我的主要内容中:

int main(){

    char* str = "Good morning!";
    char c = 'o';
    std::cout << count_x(str, c) << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我运行程序它崩溃时,我得到一个异常抛出的行

if (*p == x)
Run Code Online (Sandbox Code Playgroud)

如果我将循环更改为:

for (; *p; p++)
    if (*p == x)
        ++count;
Run Code Online (Sandbox Code Playgroud)

现在一切正常!我正在使用MSVC++ 14.0.

  • 我运行的相同代码我ideone没有得到异常,但结果总是0应该是3:

https://ideone.com/X9BeVx

Sto*_*ica 14

p != nullptr*p执行非常不同的检查.

前者检查指针本身是否包含非空地址.虽然后者检查指向的地址是否包含非0的内容.一个在循环中显然是合适的,其中缓冲区的内容被检查,而另一个则不是.

你是段错误的,因为你永远不会停止读取缓冲区(有效指针在递增时不太可能产生null).因此,您最终会访问超出缓冲区限制的方式.

  • @WonFeiHong - 是的,这是不正确的.`*p`没有指针类型,因此无法将其与`nullptr`进行比较.您尝试时会遇到编译器错误 (3认同)