20B. Hand Simulation with Pointers


Pointer diagrams and hand simulation

The only sensible way to deal with pointers is to draw diagrams. If pointer variable p contains the address of x, then we say that p points to x, and we show an arrow from p to x.

Let's simulate the following pointless sequence of statements just for practice. For reference, the lines are numbered.

  1. int x = 40;
  2. int y = 24;
  3. int* p = &x;
  4. int* q = &y;
  5. int* r = q;
  6. q = p;
  7. *r = *q;
  8. *p = 55;
  9. p = r;

The following diagram shows the variables after the first 5 lines.

After line 6, the pointer stored in p is copied into q, making q point to the same place as p.

Line 7 sets *r (currently the same as y) to hold the same value as in *q (currently x).

Line 8 sets *p (currently the same as x) to hold 55.

Line 9 copies the pointer in r (which currently points to y) into pointer variable p, making p also point to y.

You should be able to draw your own pointer diagrams and hand simulate a sequence of statements like the ones just done. The most important thing is: Don't cut corners. Draw your pointer diagrams carefully. Never try to hand-simulate pointer operations in your head. You will miss important details.


Exercises

  1. What is the value of x after doing

      int y = 7;
      int x = 35;
      int* p = &x;
      p = &y;
    
    Answer