20A. 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.

Line 6, copies the pointer that is p into q, making q point to the same place as p.

Line 7 sets *r (currently the same as y) to hold the value that is 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 variable x after performing the following sequence of statements?

      int  x = 50;
      int* p = &x;
      *p = 4;
    
    Answer

  2. What is the value of x after doing

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

  3. What is the value of variable x after performing the following sequence of statements?

      int  x = 20;
      int  y = 41;
      int  z = 60;
      int* p = &x;
      int* q = &y;
      int* r = &z;
      *r = *q;
      q = p;
      *q = *r;
    
    Answer