AlexGreat AlexGreat -4 years ago 37
C++ Question

C++ Primer Exercise

i just started to learn C++ , and come across 2 exercises in C++ Primer . 1 of this exercises i can't understand .

Exercise 2.22 C++ Primer

Assuming

p
is a pointer to
int
,explain the following code:

if (p) //....
if (*p) //....


As i understand in 1 statement we checking condition of pointer p whether its
true
or
false


In 2 statement all actions is same except this time we use dereference operator

If i'm wrong, can you tell me where my mistake.

And Next Exercise ,This exercise i cant understand

Exercise 2.23

Given a pointer
p
,can you determine whether
p
points to a valid object ? If so, how? If not , why not?

The thing i know is that when your variable initialized and have the same type as pointer then you might know is that your pointer points to valid object. And also trying to access to invalid pointer can bring to code problem and that the compiler ant find this problem.

Is there something else about this Exercise can be added ? Or my guessing is wrong ?

Thank you for your time !

Answer Source

Assuming

int *p = NULL;

Then:

if (p)

checks whether p is NULL or not and will return false.

if (*p)

checks whether (*p) == 0, i.e. the integer pointed by p is 0 or not.

if you have

int *p;

i.e., without initializing it, then p will point to random address in your memory, and

if (p)

will most of the time return true. and

if (*p)

will give undefined behavior.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download