简体   繁体   English

C ++无法将解引用的char指针与char比较

[英]C++ Can't compare dereferenced char pointer to char

I have an input string, and I want to find how many spaces are there in the string. 我有一个输入字符串,我想查找字符串中有多少空格。

Here's my code 这是我的代码

// 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;
}

However, I got an error message on the if (*ptr == ' ') line that says: Thread 1: EXC_BAD_ACCESS (code = 1, address=0x100200000) 但是,我在if (*ptr == ' ')行上收到一条错误消息,内容为: Thread 1: EXC_BAD_ACCESS (code = 1, address=0x100200000)

Isn't *ptr a char type value because ptr is a char* pointer and I dereferenced it to *ptr . *ptr不是char类型的值,因为ptrchar*指针,我已将其取消引用到*ptr If so, why the comparison is not valid? 如果是这样,为什么比较无效?

您不希望while (ptr)while (*ptr)想要while (*ptr) ,也就是说,虽然ptr指向的不是一个零字符,它标志着C样式字符串的结尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM