通过指针增量遍历C字符串

Traversal of C string through pointer incrementation

本文关键字:遍历 字符串 指针      更新时间:2023-10-16

我正在阅读Bjarne Stroustrup的C++之旅,我很难理解早期的例子。在下面的代码中,while循环用于在C风格字符串上增加指针,直到指针碰到null字符。我不明白为什么指向null字符会导致指针采用nullptr的值。它似乎应该是一个非常好的指针,恰好指向一个null值。如果这是作者的错误,我会感到惊讶,因为这本书包含在stackexchange的推荐中:最终C++图书指南和列表

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;
}

要检查空字符,应该测试*p != '',而不是p != nullptr

由于您提到的原因,它会分段。尝试:

  for (; *p; ++p)