技巧来分析C语言中的指针和指针到指针的结构? [英] Tricks to analyse pointer and pointer-to-pointer structures in C?

查看:74
本文介绍了技巧来分析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("\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);

推荐答案

在笔迹丢失的情况下,我最喜欢的技巧是使用笔和纸.
为变量绘制矩形,为指针绘制箭头.
从变量矩形绘制箭头,该矩形是指向它所指向的矩形的指针变量.

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语言中的指针和指针到指针的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆