指针和整数之间的警告比较

当我遍历字符指针并检查指针何时到达空终止符时,我收到错误。

const char* message = "hi"; //I then loop through the message and I get an error in the below if statement. if (*message == "\0") { ...//do something } 

我得到的错误是:

 warning: comparison between pointer and integer ('int' and 'char *') 

我认为message取消引用消息前面的* ,所以我得到消息指向的值? 顺便说一句,我不想​​使用库函数strcmp

它应该是

 if (*message == '\0') 

在C中,简单引号分隔单个字符,而双引号分隔字符串。

这个: "\0"是一个字符串,而不是一个字符。 角色使用单引号,例如'\0'

在这一行……

 if (*message == "\0") { 

……正如你在警告中看到的……

警告:指针和整数之间的比较
       ('int'和'char *')

…实际上是在比较intchar * ,或者更具体地说,是一个带有char地址的char

要解决此问题,请使用以下方法之一:

 if(*message == '\0') ... if(message[0] == '\0') ... if(!*message) ... 

另外,如果你想比较字符串,你应该使用在string.h找到的strcmpstrncmp

Interesting Posts