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