【问题标题】:Traversal of C string through pointer incrementation [duplicate]通过指针递增遍历C字符串[重复]
【发布时间】:2014-10-07 13:58:42
【问题描述】:

我正在阅读 Bjarne Stroustrup 的 C++ 之旅,但我无法理解早期的示例。在下面的代码中,while 循环用于递增 C 样式字符串上的指针,直到它碰到空字符。我不明白为什么指向空字符会导致指针取 nullptr 的值。看起来它应该是一个非常好的指针,恰好指向一个空值。如果这是作者错误,我会感到惊讶,因为这本书包含在 stackexchange 的推荐中:The Definitive C++ Book Guide and List

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

【问题讨论】:

  • 不会的;该代码示例是错误的
  • 书中的样本不同。循环是while(*p)。你有哪个版本?
  • 嗯,我有一个通过谷歌搜索“A Tour of C++ pdf”找到的版本(第一个结果)。我猜对我来说是对的,虽然有趣的是它声称是 2014 年的文案。
  • 根据errata,“count_if() 的代码错误”,第一次打印,第二次修复。

标签: c++ arrays pointers c-strings


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

      for (; *p; ++p)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 2011-04-17
      相关资源
      最近更新 更多