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)
该功能无效.您的本书版本包含错误.正确的版本测试*p的while条件.
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.