开发者

Difference between these two statements? - C++

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, w开发者_Python百科hat's the difference between these two statements? When would each of them return true/false?

if (some_ptr ==  NULL)

if (*some_ptr == NULL)

Thanks!


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜