Question

I'm a programming student trying to better understand pointers, one of the things I learned is that you can set a pointer to NULL. My question is, what's the difference between these two statements? When would each of them return true/false?

if (some_ptr ==  NULL)

if (*some_ptr == NULL)

Thanks!

Was it helpful?

Solution

The first does a comparison against the address of the variable to null, the second dereferences the pointer, getting the value held at it and compares it against null.

OTHER TIPS

The first statement refers to the actual adress the pointer some_ptr is pointing to. In case it's NULL ( the value represented by the define NULL ), it's true, otherwise not.

The latter statement refers to the content at the adress the pointer is pointing to. So if you're having some_ptr point to an integer, and that integer happens to be the same as your null define, the second condition evaluates to true.

The first is you are comparing the pointer itself against NULL, which seems desirable.

The second is that you are first dereferencing the pointer to get the value which is then compared against NULL, like you are comparing an int value to 0. based on your variable name.

The first says:
Is some_ptr NULL?

The second says:
Is whatever some_ptr is pointing to NULL?

For eg: int* x; Here if you like check if x points to NULL then we use the first statement. With the same int* x, if you use the second statement, then you are trying to dereference the pointer and check for the value that x points to. Because NULL is 0 in C, C++ it checks for the value 0 that x points to.

EDIT: Also with the second statement, if x points to NULL, then deferencing a NULL pointer results in a core drop on UNIX.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top