gpt4 book ai didi

c++ - 为什么来自 Bjarne 的 "Tour of C++"的代码有效?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:13:59 24 4
gpt4 key购买 nike

如果我们将一个数组传递给函数,我们将遍历它直到“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;
}

最佳答案

该函数无效。您的图书版本有误。正确的版本在 while 条件下测试 *p

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

更新:代码显然在打印和 the errata for the first printing 之间发生了一点变化提到与此功能相关的错误。向@BenVoigt 致敬。

关于c++ - 为什么来自 Bjarne 的 "Tour of C++"的代码有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29461790/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com