中分析指针和指针到指针结构的技巧

中分析指针和指针到指针结构的技巧

本文介绍了在 C 中分析指针和指针到指针结构的技巧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下代码,是否有解决它的技巧(图形、图表或一些更简单的分步说明)或任何类似的指针问题?
我的意思是我已经知道答案了,只是我计算的时间太长了.

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("
 %d %d %d",ptr-p, *ptr-data, **ptr);
*ptr++;
printf("
 %d %d %d",ptr-p, *ptr-data, **ptr);
*++ptr;
printf("
 %d %d %d",ptr-p, *ptr-data, **ptr);
++*ptr;
printf("
 %d %d %d",ptr-p, *ptr-data, **ptr);

推荐答案

我最喜欢的技巧是使用笔和纸.
为变量绘制矩形,为指针绘制箭头.
从变量矩形(即指针变量)绘制箭头指向它所指向的矩形.

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.

它在 ASCII 艺术中不像在纸上那样直观,但看起来有点像这样.

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

注意 ptr 从不指向 p 中的索引 4,而是索引 3 中的指针递增,因此它指向数据的索引 4.(诚​​然,我并没有真正深入到那个细节,我的问题集中在技巧上,而不是在你的代码上做的结果.我可能误读了故意难以阅读的运算符使用......)

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

这篇关于在 C 中分析指针和指针到指针结构的技巧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 21:36