sop sop - 3 months ago 9
C Question

Comparing pointer with char end of string

I know that when comparing a char pointer with some char value you need to prefix the pointer with

*
, but I have found in some code a comparison like:

char* c;
// ...
while (*c != ']' && *c != '\0') // search for some character
{
c++;
}
if (c == '\0')
{
return -1; // error
}


So, my question is: is this a bug or a special case? Shouldn't there be
if (*c == '\0')
there?

Answer

Null Pointers

The integer constant literal 0 has different meanings depending upon the context in which it's used. In all cases, it is still an integer constant with the value 0, it is just described in different ways.

If a pointer is being compared to the constant literal 0, then this is a check to see if the pointer is a null pointer. This 0 is then referred to as a null pointer constant. The C standard defines that 0 cast to the type void * is both a null pointer and a null pointer constant.

Additionally, to help readability, the macro NULL is provided in the header file stddef.h.

Therefore, here are some valid ways to check for a null pointer:

if (pointer == NULL)

NULL is defined to compare equal to a null pointer. It is implementation defined what the actual definition of NULL is, as long as it is a valid null pointer constant.

if (pointer == 0)

0 is another representation of the null pointer constant.

Null Characters

'\0' is defined to be a null character - that is a character with all bits set to zero. This has nothing to do with pointers. However you may see something similar to this code:

if (!*string_pointer)

checks if the string pointer is pointing at a null character

if (*string_pointer)

checks if the string pointer is pointing at a non-null character.

So, my question is: is this a bug or a special case? Shouldn't there be if (*c == '\0') there?

The statement in your code if (c == '\0') checks if the pointer itself equals 0. That is, it checks for c being a Null pointer. But I think it is a bug, because the statement to check if c is a NULL pointer is after accessing the value stored at c. I think the program is about to locate a character ]. If it found the character ] before the null character, then it doesn't return -1. So, the corrected statement should be-

if (*c == '\0')
{
    return -1; // It didn't found the '[' character!
}