Tricks to analyse pointer and pointer-to-pointer structures in C?

My favorite trick for situations in which I lose track of pointers, is using pen and paper.
Draw rectangles for variables and arrows for pointers.
Draw the arrow from the variable-rectangle which is the pointer variable to the rectangle it points to.

It does not work quite as intuitively in ASCII art as on paper, but it looks somewhat like this.

data [ 0 ][ 1 ][ 2 ][ 3 ][ 4 ]
       ^    ^    ^    ^   ^^
       |    |    |    |.../|     ("..." meaning chronologically progressing,
       |    |    |    "https://stackoverflow.com/"            though this one is the fourth step)
       |    |    |    "https://stackoverflow.com/"
p    [ | ][ | ][ | ][ |/][ | ]

       ^    ^    ^    ^ 
       |... |... |... |             (here are the first three steps)
      ptr

Note that ptr never points to index 4 in p, but instead the pointer in index 3 is incremented, so that it points to index 4 of data. (Admittedly I did not really go to that detail, I focus my question on the trick, not the result of doing it on your code. I might have misread the intentionally hard to read operator uses…)

Leave a Comment