Home Page

Learning C++ Pointers for REAL Dummies

Introduction

How do I point to the neighbor?

What if we have a pointer pointing to some address, but we want to know what are the values around it. You might be thinking, "Why would we want to do that?" Well, let's say we declared an array. And we wanted to point to the second element. But, then, farther down we wanted to point to the third element. This is how we would do it:

int a[5] = {1,2,3,4,5};
int *p1;
p1 = &a[1]; // gets address of this element
printf("*p1 = %d\n", *p1);
p1++; // point to the next element
printf("*p1 = %d\n", *p1);

Click here to see the answer. And if we wanted to go back an element it would be:

p1--;

Remember, that the position of the (++) and (--) operators in respect to the variable matters. For example, if I wrote:

int *p2;
p1 = &a[1];
p2 = p1++;

p2 would not point to the third element, but actually to the second element since the (++) operator is after the variable it is done after the assign (=) operator. So *p1 would equal 3 while *p2 would equal 2.

You might now be thinking, "Well if I wanted to point two elements down, I would have to do 'p1++' twice?" And I would say, "That is a very good question. The answer to your question is no."

Pointers are able to do math. Continuing from the first example:

p1 = &a[1];
printf("*p1 = %d\n", *p1);
p1 = p1+2;
printf("*p1 = %d\n", *p1);

This would print out:

*p1 = 2
*p1 = 4

The pointer knows to go down two houses. Pointers can also get the value of an address for another variable, report it, but still point to the same place. Let's see an example:

p1 = &a[1];
int dave;
dave = *(p1+2);
printf("*p1 = %d\n", *p1);
printf("dave = %d\n", dave);

What do you think is printed out. Click here to see the answer.

As you probably can already tell, arrays and pointers seem to be almost brothers. See You guys are brothers? for a better explanation of how arrays and pointers are related.

 

 

Where do you live? (&)
What you got in your house? (*)
Don't point, it's rude!
I am pointing here!
Where are you pointing?
How do I point to the neighbor?
You guys are brothers?
Beam me up Scotty, multiple times!!!
Quiz for REAL Dummies