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



当我迭代字符指针并检查指针何时到达空终止符时,我得到一个警告。

 const char* message = "hi";
 //I then loop through the message and I get an error in the below if statement.
 if (*message == "") {
  ...//do something
 }
我得到的错误是:
warning: comparison between pointer and integer
      ('int' and 'char *')

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

应该是

if (*message == '')

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

此:""是字符串,而不是字符。字符使用单引号,如''

这一行…

if (*message == "") {

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

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

…您实际上是将intchar *进行比较,或者更具体地说,将地址指向charint进行比较。

要解决这个问题,可以使用以下命令之一:

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

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

最新更新