为什么这段代码不起作用?,我使用了“A Tour of C++”中的函数,它告诉我当数组结束时指针指向 nullptr 简要解释。我试图实现它,但它没有显示任何内容。提前致谢。
#include <iostream>
int count_x(char* p, char x)
{
int count = 0;
while (p)
{
if (*p == x){++count;}
p++;
}
return count;
}
int main()
{
char my_string[] {"hello world"};
char* my_string_ptr {my_string};
std::cout << "There are " << count_x(my_string_ptr,'a') << " a in the string\n";
return 0;
}```
Run Code Online (Sandbox Code Playgroud)
不,数组末尾的指针不为空。你可能想要:
while (*p)
Run Code Online (Sandbox Code Playgroud)
这与
while (*p != '\0')
Run Code Online (Sandbox Code Playgroud)
和
while (*p != 0)
Run Code Online (Sandbox Code Playgroud)
正在测试空字符。