康斯特指针C++斯特劳斯特鲁普


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 是一个指针。常量表示指针无法修改。但是在 for 循环中,有 ++p,这意味着指针正在迭代/递增以访问值 *p

那里有一个矛盾 - p 不能修改,但它正在增加/修改?

C++中的声明从右到左读取。所以像

const char* p

将改为:p是指向const char的非常量指针。

显然,p不是const,但它所指向的是const。所以*p = 's'是非法的,但p++不是。

最新更新