开发者

Tricky pointer question

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:

A C programmer is working with a little-endian machine with 8 bits in a byte and 4 bytes in a word. The compiler supports unaligned access and uses 1, 2 and 4 bytes to store char, short and int respectively. The programmer writes the following definitions (below right) to access values in main memory (below left):

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 di开发者_Go百科d this

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

Thanks in advance for any help.


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


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜