Tricky pointer question

匿名 (未验证) 提交于 2019-12-03 02:51:02

问题:

I'm having trouble with a past exam question on pointers in c which I found from this link, http://www.cl.cam.ac.uk/teaching/exams/pastpapers/y2007p3q4.pdf

The question is this:

Address Byte offset
---------0 --1-- 2-- 3
0x04 | 10 00 00 00
0x08 | 61 72 62 33
0x0c | 33 00 00 00
0x10 | 78 0c 00 00
0x14 | 08 00 00 00
0x18 | 01 00 4c 03
0x1c | 18 00 00 00

int **i=(int **)0x04;   short **pps=(short **)0x1c;    struct i2c {   int i;   char *c;   }*p=(struct i2c*)0x10;

(a) Write down the values for the following C expressions:

**i   p->c[2]   &(*pps)[1]   ++p->i  

I get

**i == 0xc78   p->c[2] == '62'   ++p->i == 0x1000000  

I don't understand the third question (&(*pps)[1]), could someone please explain what is going on here? I understand the pps pointer has been dereferenced but then the address of operator has been applied to the value. Isn't that just like asking for the adress of a constant, for example if I did this

int i = 7;   int *p = &i; &(*p)   //would this mean address of 7??  

Thanks in advance for any help.

回答1:

The [] operator takes precedence over the & operator. So the code is dereferencing pps to get to the first element of an array of short*. Since this element is also a pointer, we may treat it as an array and look up the element one position to the right of what it points to, wth [1]. Finally, we take the address of that element.

It might be useful to note that &p[i] is the same as p + i - it gives you a pointer to the element i positions to the right of where p points to.

The intermediate values are:

pps == 0x1c *pps == 0x18 &(*pps)[1] == *pps + 1 == 0x1A

(the +1 adds two bytes, since it is used on a short*)



回答2:

The expression is parsed as &((*pps)[1]); pps is being treated as a pointer to an array, you're accessing the first element of that pointed-to array, and then taking the address of that element.



回答3:

pps is a pointer to pointer to short,

which means that *pps is a pointer to short (or array of shorts),

(*pps)[1] is just like *(*pps + 1) [pointers arithmetic],

and &(*(*pps + 1)) is the address of *(*pps+1),

or, in other words - (*pps+1) (which is a pointer to short).



回答4:

pps is a pointer to a pointer. It is dereferencing pps. So now you have a pointer. As arrays are just pointers you are then using pps as an array.

It is then same as:

short ps[2] = {0x0001,0x034c}; short **pps = &ps;

so the result is: 0x034c



转载请标明出处:Tricky pointer question
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!