为什么Bjarne的"Tour of C++"代码有效?

Lea*_*ath 4 c++ arrays pointers

如果我们将一个数组传递给函数,我们迭代它直到"p"是一个nullptr.但这绝不会发生,因为数组中值为0的最后一个元素之后的地址不是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-ter minated array of char (or to nothing)
{
  int count = 0;
  while (p) {
    if (*p==x)
      ++count;
    ++p;
  }
  return count;
}
Run Code Online (Sandbox Code Playgroud)

rob*_*off 7

该功能无效.您的本书版本包含错误.正确的版本测试*pwhile条件.

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)
{
    int count = 0;
    while (*p) {
//         ^----------------- You omitted this asterisk.
        if (*p==x)
            ++count;
        ++p;
    }
    return count;
}
Run Code Online (Sandbox Code Playgroud)

更新:代码显然在打印之间有所改变,第一次打印的勘误提到了与此功能相关的错误.帽子提示@BenVoigt.

  • 然后你有一个糟糕的电子书版本.转到[亚马逊的平装版](http://www.amazon.com/Tour-In-Depth-Series-Bjarne-Stroustrup/dp/0321958314),点击封面"Look Inside",然后输入" "在搜索框中显示".您将看到打印版本(第12页)与我的答案相符. (3认同)
  • 不,我没有写错.以下是该书的截图:http://postimg.org/image/5quxkcnhf/ (2认同)