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

后端 未结 1 1138
梦毁少年i
梦毁少年i 2020-12-02 01:11

Given the following code, is there a trick (a graph, a diagram or some easier step by step instructions) to solve it or any similar pointer question?
I mean I already kn

相关标签:
1条回答
  • 2020-12-02 01:57

    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,
           |    |    |    |  / |            though this one is the fourth step)
           |    |    |    | /  |
    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...)

    0 讨论(0)
提交回复
热议问题