【发布时间】:2018-09-24 01:15:30
【问题描述】:
int count_x(const 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!=0; ++p)
if (*p==x)
++count;
return count;
}
p 是一个指针。 const 意味着指针不能被修改。但是在for循环中,有++p,这意味着指针被迭代/递增以访问值*p
那里有一个矛盾 - p 不能被修改,但它正在递增/修改?
【问题讨论】:
-
不,
const表示无法修改事物指针。您仍然可以更改指针。 -
那个 const 意味着
p指向的是 const,而不是p本身。对于您所描述的内容,const 需要位于*的另一侧。 -
@mrunion 不,它没有。
-
我想知道你为什么觉得有必要在你的问题中包含 Stroustrup 的名字..
-
@user3738870 代码来自 Stroustrup 的 A Tour of C++。