为什么在这种情况下递增阵列名称有效?

Why Incrementing Array name works in this case?

本文关键字:有效 阵列 这种情况下 为什么      更新时间:2023-10-16

我了解到数组名称被视为常量指针,因此不能递增。但是,我发现它在这种情况下工作:当数组作为函数的参数传递时,在函数内部,数组的名称可以递增。有人可以解释为什么这有效吗?

这是代码:

using namespace std;
unsigned int c_in_str(const char* str, char ch);
int main()
{
char mmm[15] = "minimum";
unsigned int ms = c_in_str(mmm, 'm');
cout << "m counts: " <<ms;
return 0;
}
// this function counts the number of ch characters    
unsigned int c_in_str(const char* str, char ch)
{
unsigned int count = 0;
while (*str)        // quit when *str is ''
{
if (*str == ch)
count++;
str++;        // how come this works with array name?
}
return count;
}

确实不能递增数组,但str指针而不是数组。

你可以通过查看 减速const char* str.奇怪的是,即使您将声明更改为此const char str[]str仍然是一个指针。在 C++(或 C(中不可能将数组作为参数。