29

I am getting a warning 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.

klutt
  • 30,332
  • 17
  • 55
  • 95
catee
  • 401
  • 1
  • 4
  • 4
  • 1
    Note that `"\0"` is a string with two consecutive null bytes (so the second can't be found by string manipulating functions such as `strlen()` because they stop at the first null byte). The empty string `""` consists of a single null byte. – Jonathan Leffler Sep 10 '15 at 20:07

3 Answers3

68

It should be

if (*message == '\0')

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

blakelead
  • 1,780
  • 2
  • 17
  • 28
  • Oh, so the double quotes make the difference? Thanks I'm able to compile successfully now. – catee Sep 10 '15 at 19:37
  • 4
    I'm happy to help. The warning means that you are trying to compare a character with a string, hence the "comparison between pointer (string) and integer (character)" message. – blakelead Sep 10 '15 at 19:41
9

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

dbush
  • 205,898
  • 23
  • 218
  • 273
8

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.

Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46