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

时间:2015-09-10 19:33:07

标签: c null-terminated

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

 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

3 个答案:

答案 0 :(得分:32)

应该是

if (*message == '\0')

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

答案 1 :(得分:8)

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

答案 2 :(得分:5)

在这一行......

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

......正如你在警告中看到的那样......

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

...您实际上正在将intchar *进行比较,或者更具体地说,将intchar的地址进行比较。

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

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

在旁注中,如果您想比较字符串,则应使用strcmp中的strncmpstring.h

相关问题