如何正确使用 nullptr?

How to use nullptr properly?

目前我正在阅读 Byarne Stroustrup 的 "A tour of C++"。重要的是:在 "pointers, arrays and references" 上,他举了一个使用 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;
}

我的主要是:

int main(){

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

    return 0;
}

当我 运行 程序崩溃时,我在第

行抛出异常
if (*p == x)

如果我把循环改成这样:

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

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

https://ideone.com/X9BeVx

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

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

你犯了段错误,因为你从不停止读取缓冲区(一个有效的指针在递增时不太可能产生空值)。所以你最终访问的方式超出了你的缓冲区限制。

请记住,您使用的是 C 语言功能。

您的问题出在 for 循环中。在指针到达 字符数组的最后一个元素后 它指向数组的末尾而不是 nullptr.

假设您有一个字符数组,例如 const char *a ="world" 并且 ptr 指向

     +-----+     +---+---+---+---+---+---+
ptr :| *======>  | w | o | r | l | d |[=10=] |
     +-----+     +---+---+---+---+---+---+  

ptr 指向的最后一个元素是 '[=16=]' 并且在您的 for 中您应该更改代码如下:


for (; *p != 0; p++) {
        if (*p == x)
            ++count;
    }

输出:3