C++ pointer assignment

I'd like to share a general technique that I used to learn how pointers work when I was starting out. If you apply it to your problem, you'll see the answer as plain as day.

Get a big sheet of graph paper and lay it lengthwise on the table in front of you. This is your computer's memory. Each box represents one byte. Pick a row, and place the number '100' below the box at far left. This is "the lowest address" of memory. (I chose 100 as an arbitrary number that isn't 0, you can choose another.) Number the boxes in ascending order from left to right.

+---+---+---+---+---+--
|   |   |   |   |   | ...
+---+---+---+---+---+--
100  101 102 103 104  ...

Now, just for the moment, pretend an int is one byte in size. You are an eight-bit computer. Write your int a into one of the boxes. The number below the box is its address. Now choose another box to contain int *b = &a. int *b is also a variable stored somewhere in memory, and it is a pointer that contains &a, which is pronounced "a's address".

int  a = 5;
int *b = &a;
  a       b 
+---+---+---+---+---+--
| 5 |   |100|   |   | ...
+---+---+---+---+---+--
 100 101 102 103 104  ...

Now you can use this model to visually work through any other combinations of values and pointers that you see. It is a simplification (because as language pedants will say, a pointer isn't necessarily an address, and memory isn't necessarily sequential, and there's stack and heap and registers and so on), but it's a pretty good analogy for 99% of computers and microcontrollers.

So in your case,

int x = 35;
int y = 46;
  x   y 
+---+---+---+---+---+--
| 35| 46|   |   |   | ...
+---+---+---+---+---+--
 100 101 102 103 104  ...
int *p = &x;
int *q = &y;
  x   y   p   q
+---+---+---+---+---+--
| 35| 46|100|101|   | ...
+---+---+---+---+---+--
 100 101 102 103 104  ...
p = q;
  x   y   p   q
+---+---+---+---+---+--
| 35| 46|101|101|   | ...
+---+---+---+---+---+--
 100 101 102 103 104  ...
*p = 90;
  x   y   p   q
+---+---+---+---+---+--
| 35| 90|101|101|   | ...
+---+---+---+---+---+--
 100 101 102 103 104  ...

Now what is *p? What is *q?


Because q is the address of y. And after p=q, p also becomes the address of y. That is why p and q print the same address when you print them using cout.

In other words, both p and q point to the same variable y. So if you change the value of any of y, *p or *q, then the change will occur in all, because all of them are same!

Tags:

C++

Pointers