Question:easy

Consider the following ANSI-C program.
#include <stdio.h>
int 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);
return(0);
}
The output of this program is ____________. (answer in integer)
Note: Assume that the program compiles and runs successfully.

Show Hint

Track carefully which variable \(ptr\) is aliasing at each step - it points first to \(a\), then is redirected to \(c\). Remember \(*(&b)\) simplifies to just \(b\).
Updated On: Aug 3, 2026
Show Solution

Correct Answer: 9

Solution and Explanation

An alternative way to solve this is to maintain a small table of variable values after every statement, instead of purely symbolic substitution.

Step 1: Initialization

After the declarations and first assignment line, the table of values is: \(a = 5\), \(b = 11\), \(c = 20\).

Step 2: Pointer aliasing

The statement ptr = &a; makes \(ptr\) an alias for the memory cell holding \(a\). Any write through \(ptr\) now changes \(a\), and any read through \(ptr\) now reads \(a\).

Step 3: Indirect write

The statement *ptr = c; copies the value stored in \(c\) (namely 20) into the cell that \(ptr\) aliases, which is \(a\). Updated table: \(a = 20\), \(b = 11\), \(c = 20\).

Step 4: Re-aliasing

The statement ptr = &c; now makes \(ptr\) an alias for \(c\) instead of \(a\). The value of \(a\) that was just set (20) is not touched again by this line - it simply changes what \(ptr\) points to going forward.

Step 5: Direct assignment

The statement a = *(&b); reduces to \(a = b\), since taking the address of \(b\) and then dereferencing it just yields \(b\) itself. So \(a\) is overwritten with \(11\). Updated table: \(a = 11\), \(b = 11\), \(c = 20\).

Step 6: Final computation

The statement c = *ptr - a; reads \(*ptr\), which is the value of \(c\) since \(ptr\) now aliases \(c\). That value is still \(20\) (it was never modified after Step 3). So we compute \(c = 20 - 11 = 9\).

Step 7: Output

The final value printed is \(c = 9\), which matches the official key of 9.

Was this answer helpful?
0


Questions Asked in GATE CS exam