Tracing pointer reassignment in C
Pointers & Memory

Answer & solution
Official answer: 9
Step through it (14 steps)
Givens and goal
Find the printed c for this statement sequence in main: int *ptr,a,b,c; a=5; b=11; c=20; ptr=&a; *ptr=c; ptr=&c; a=*(&b); c=*ptr-a; printf("%d",c);. Assume successful compilation and execution.
Approach
Track both the pointer target and the object values after every assignment.
Step-by-step solution
1. Initially a=5,b=11,c=20. The assignment ptr=&a stores a’s address in ptr; it does not change any integer value.
2. Then *ptr=c writes the current value of c into the object pointed to by ptr, which is a. The state becomes a=20,b=11,c=20, with ptr still pointing to a.
3. Next ptr=&c redirects the pointer to c without copying any old pointed-to value. The expression *(&b) is simply b, so a=*(&b) sets a=11. Now a=11,b=11,c=20 and ptr points to c.
4. In c=*ptr-a, the right-hand side reads the old value c=20 through ptr and subtracts a=11. The assignment therefore stores c=9, and printf prints 9.
5. This assignment is well-defined: the old c is read to calculate its new value. The crucial distinction is between changing ptr itself and assigning through *ptr to the current target.

![Question 21, GATE 2022: Find the output of this ANSI C main body: int x=1,z[2]={10,11}; int *p=NULL; p=&x; *p=10; p=&z[1]; *(&z[0]+1)+=3; printf("%d, %d, %d\n",x,z[0],z[1]); return 0; (stdio.h included). A 1,10,11; B 1,10,14; C 10,14,11; D 10,10,14.](../../../assets/questions/CS-2022-Q21-1.webp)


