【发布时间】:2016-06-21 01:29:34
【问题描述】:
我对 A Tour of 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;
}
// The definition of count_x() assumes that the char* is a C-style string,
// that is, that the pointer points to a zero-terminated array of char.
我知道如果 p 未分配,count_x 应该终止,并且当它到达 p 引用的 C 样式字符串的末尾时,for 循环应该终止。
但是,当我构建一个使用 count_x() 的主函数时,它似乎永远不会正确终止:
int main () {
char teststring[] = {'b', 'l', 'a', 'h', '\0'};
cout << "teststring is: " << teststring << endl;
cout << "Number of b's is: " << count_x(teststring, 'b') << endl;
return 0;
}
执行此操作会打印大量垃圾,然后以分段错误退出。如果我用for (; *p!='\0'; ++p) 替换count_x 中的for (; p!=nullptr; ++p),它会正确执行。我猜这意味着字符串没有正确终止。如果是这样,我如何终止 C 风格的字符串,以便可以在这里使用 nullptr?
编辑:在 cmets 中有一个讨论澄清了这种情况。我使用的是 2013 年 9 月以来这本书的第一次印刷,上面的印刷有误。从 2015 年 1 月开始的第三版(链接在 cmets 中)有更正的示例,它使用 for (; *p!=0; ++p) 而不是 for (; p!=nullptr; ++p)。该更正也记录在本书的勘误表中。谢谢!
Edit2:对不起,伙计们,这显然已经在早些时候在这里问过:Buggy code in "A Tour of C++" or non-compliant compiler?
【问题讨论】:
-
您发布的
count_x功能已损坏。nullptr不能那样工作。 -
该代码已损坏。忽略它。他们可能是指
for (; *p != 0; ++p)。 -
本书seems to use a while loop。你用的是什么版本?
-
@imallett:上一页,还有一个带有
for循环的版本,但该版本使用正确的测试而不是与nullptr进行比较。 -
勘误表中可能有错误,或者第一版可能使用了不同的函数名称。除了名称之外,这似乎与第 1 章的第一版勘误表相匹配:“pp 11-12:count_if() 的代码是错误的(没有按照它声称的那样做)......”页码似乎匹配。
标签: c++ c pointers c++11 c-strings