1

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 know the answer, it just took me too long to calculate.

static int data[] = {0,1,2,3,4}
int*p[] = {data,data+1,data+2,data+3,data+4};
int**ptr=p;
ptr++;
printf("\n %d %d %d",ptr-p, *ptr-data, **ptr);
*ptr++;
printf("\n %d %d %d",ptr-p, *ptr-data, **ptr);
*++ptr;
printf("\n %d %d %d",ptr-p, *ptr-data, **ptr);
++*ptr;
printf("\n %d %d %d",ptr-p, *ptr-data, **ptr);
3
  • 1
    Confusing that you made data[] static. And you forgot the semicolon. Commented Nov 29, 2019 at 1:23
  • Here's one trick: compile the code, run it through your debugger step by step and watch all variables involed. Approximately 100 times faster than staring at the code and making notes with pen and paper. Commented Nov 29, 2019 at 12:08
  • What if you are in an interview haha ? Commented Nov 29, 2019 at 18:29

1 Answer 1

3

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...)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.