Query about pointers on Cplusplus

I think I have a basic understanding of pointers now having read the first section of the cplusplus article, however I am confused by the outcome of this piece of code in the middle of the Declaring Pointers section. I have tried running the code in VS and using breakpoints at every line to check how it works, but the last lines confuse me.

Line 14: p1=p2; it took me a moment to realise that this means the value of the pointer itself, not the value the pointer is referencing. So p2 is now pointing at the same value as p1.

Line 15: *p1 = 20; The value p1 is looking at is set to 20. It was previously set to 10 in line 12.

So why at lines 17 and 18 is firstvalue = 10, not 20?
And why is secondvalue = 20 and not 10?

WAIT A MINUTE! I think I figured it out - I was going to delete this but Iā€™'l leave it for people to follow my rambling thoughts. I assumed Line 14 made p2 look at the same value as p1. Actually its the opposite; p1 is made to look at the same value as p2. So firstvalue remains at 10 from line 12, and *p1 = *p2 = secondvalue = 20. Phew :slight_smile:

2 Likes

In regards to line 14: p1 = p2;

This actually means that pointer 1 is now looking at pointer 2. Not the values like you mentioned. Here is a good link for reading up on some pointers.

Privacy & Terms