C++无法将dereferenced char指针与char进行比较

Hei*_*erg -1 c++ string xcode6

我有一个输入字符串,我想找到字符串中有多少个空格.

这是我的代码

// input string
std::string str = "abc d e f";

// convert string to cstring
char* cstr = new char[str.length()+1];
std::strcpy(cstr, str.c_str());

// iterate through the cstring and count how many spaces are there
int num_of_spaces = 0;
char* ptr = cstr;

while (ptr) {
    if (*ptr == ' ') {
        ++num_of_spaces;
    }
    ++ptr;
}
Run Code Online (Sandbox Code Playgroud)

但是,我在该if (*ptr == ' ')行上收到一条错误消息:Thread 1: EXC_BAD_ACCESS (code = 1, address=0x100200000)

不是*ptrchar类型值,因为它ptr是一个char*指针,我将其取消引用*ptr.如果是这样,为什么比较无效?

Dav*_*rtz 5

你不while (ptr)想要while (*ptr),也就是说,当事物ptr指向的不是一个标记C风格字符串结尾的零字符.