数组结束时指针不应该指向nullptr吗?

为什么这段代码不起作用?,我使用了“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 stringn";

    return 0;

}``` 

回答

不,数组末尾的指针不为空。你可能想要:

while (*p) 

这与

while (*p != '')

while (*p != 0)

正在测试空字符。


以上是数组结束时指针不应该指向nullptr吗?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>