C Pointers Past Paper -
i'm looking @ past paper course i'm doing @ university, , there question c pointers.
i reckon have reasonable grasp of how work, question confusing me:
consider running c program fragment: int x[4] = {0,2,4,6}; int *y; y = &x[2]; *(x + 2) = y[1] + 1; value of expression *y afterwards? (a) 2 (b) 4 (c) 5 (d) 7 (e) 8
now, in answers said question, says answer d
.
i'm super confused, seeing as:
- the value of x not declared, i'd have thought impossible evaluate
x+2
y
isn't array, how cany[1]
evaluated?
why 7
correct answer here?
lets break down:
int x[4] = {0,2,4,6};
x [0] = 0 x [1] = 2 x [2] = 4 x [3] = 6
int *y; pointer integer y point location in x
x [0] = 0 // <-- y ? x [1] = 2 // <-- y ? x [2] = 4 // <-- y ? x [3] = 6 // <-- y ?
y = &x[2]; have specified y points x[2]
x [0] = 0 x [1] = 2 x [2] = 4 // <-- y (or y[0]) x [3] = 6
*(x + 2) same x[2] so: x[2] = y[1] + 1;
x [0] = 0 x [1] = 2 x [2] = 4 // <-- x[2] x [3] = 6 // <-- y[1]
y[1] 6, y[1] + 1 = 7
note y[1] same *(y + 1). take address y points too, add size of 1 integer , obtain contents of points to.
Comments
Post a Comment