Warning comparison between pointer and integer

一个人想着一个人 提交于 2019-12-03 15:54:12

问题


I am getting an error when I iterate through the character pointer and check when the pointer reaches the null terminator.

 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
 }

The error I am getting is:

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

I thought that the * in front of message dereferences message, so I get the value of where message points to? I do not want to use the library function strcmp by the way.


回答1:


It should be

if (*message == '\0')

In C, simple quotes delimit a single character whereas double quotes are for strings.




回答2:


This: "\0" is a string, not a character. A character uses single quotes, like '\0'.




回答3:


In this line ...

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

... as you can see in the warning ...

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

... you are actually comparing an int with a char *, or more specifically, an int with an address to a char.

To fix this, use one of the following:

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

On a side note, if you'd like to compare strings you should use strcmp or strncmp, found in string.h.



来源:https://stackoverflow.com/questions/32510218/warning-comparison-between-pointer-and-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!