HyperionX
HyperionX

Reputation: 1646

Check for null character C++

I'm trying to test if the value stored in a particular memory address is NULL, I have this and in debug it's showing the char value in that address as '\0'. Yet it's always skipping over this IF statement.

Is this the right syntax to use? I have ensured that the address is set to null.

if (test->address + length == NULL)
{
    ..code..
}

Upvotes: 1

Views: 6535

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

If I have understood you correctly then the valid statement will look like

if ( *( test->address + length ) == '\0' )
{
    ..code..
}

Or

if ( test->address[length] == '\0' )
{
    ..code..
}

provided that type of object test->address either defined as a character array or a pointer of type char *

Upvotes: 4

Mateusz Grzejek
Mateusz Grzejek

Reputation: 12058

Of course it skips this if. That's because pointers arithmetic rules.

  • test->address is a pointer
  • test->address + length is test->address + sizeof(T) * length, where T is the type of address.

Change:

if (test->address + length == NULL)
{
    ..code..
}

to

if (test->address[length] == 0)
{
    ..code..
}

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254461

Assuming address is a char* pointer (or a char[] array), you need to dereference it to access the char values. That's

*(test->address + length)

or equivalently

test->address[length]

Upvotes: 7

Related Questions