23

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

 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 *')

我还以为*前面的messagedereferences message,那么我得到message指向的值呢?顺便说一句,我不想​​使用库函数strcmp

4

3 回答 3

59

它应该是

if (*message == '\0')

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

于 2015-09-10T19:35:05.487 回答
9

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

于 2015-09-10T19:36:52.467 回答
7

在这一行...

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

...正如您在警告中看到的...

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

...您实际上是在将 anint与 a进行比较char *,或者更具体地说,将int带有地址的an 与 a 进行比较char

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

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

附带说明一下,如果您想比较字符串,您应该使用strcmpor strncmp,在string.h.

于 2015-09-10T19:49:20.533 回答