如何正确使用nullptr

How to use nullptr properly?

本文关键字:nullptr 何正确      更新时间:2023-10-16

目前,我正在阅读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;
}

在我的主我的主要内容:

int main(){
    char* str = "Good morning!";
    char c = 'o';
    std::cout << count_x(str, c) << std::endl;
    return 0;
}

当我运行程序崩溃时,我会在line

上获得异常
if (*p == x)

如果我将循环更改为这样:

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

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

  • 我在ideone上运行的相同代码我没有例外,但是结果始终是0,应该是3

https://ideone.com/x9bevx

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

前者检查指针本身包含一个非编号地址。虽然后者检查指向的地址是否包含一个不是0的东西。一个在循环中显然是合适的,其中检查了缓冲区的内容,而另一个则没有。

您的segfault是因为您永远不会停止阅读缓冲区(有效的指针在增加时不太可能产生NULL)。因此,您最终会访问超出缓冲区限制的方式。

请记住,您正在使用C语言功能。

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

想象您有一个字符数组,例如const char *a ="world"ptr指向

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

ptr 指向的最后一个元素是'',在您的for中,您应该更改代码如下:


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

输出:3