Pointer increments and self-referential structures in C (Turbo C under DOS): predict the output of this program.\n\n#include<stdio.h>\n\nint main()\n{\n struct s1 {\n char *z;\n int i;\n struct s1 *p;\n };\n\n static struct s1 a[] = {\n {"Nagpur", 1, a+1},\n {"Chennai", 2, a+2},\n {"Bangalore", 3, a }\n };\n\n struct s1 ptr = a;\n printf("%s,", ++(ptr->z)); // advance z inside a[0]\n printf(" %s,", a[(++ptr)->i].z); // move ptr to a[1], index by its i\n printf(" %s", a[--(ptr->p->i)].z); // pre-decrement a[2].i then index\n return 0;\n}

Difficulty: Hard

Correct Answer: agpur, Bangalore, Bangalore

Explanation:


Introduction / Context:
This exercises pointer arithmetic on strings, pre-increment/decrement operators, and navigation through a self-referential array of structures. It is a classic test of sequence points and evaluation in C under Turbo C, but the logic is standard C.


Given Data / Assumptions:

  • a[0] = {"Nagpur", 1, a+1}
  • a[1] = {"Chennai", 2, a+2}
  • a[2] = {"Bangalore", 3, a}
  • ptr initially points to a[0].


Concept / Approach:
Understand that ++(ptr->z) increments the char inside a[0]; (++ptr)->i increments the struct pointer before indexing; and --(ptr->p->i) decrements the i field inside a[2] through the link from a[1].


Step-by-Step Solution:
1) ++(ptr->z): "Nagpur" becomes pointer to "agpur" ⇒ prints "agpur,".2) (++ptr) moves ptr to a[1]; ptr->i is 2 ⇒ a[2].z = "Bangalore" ⇒ prints " Bangalore,".3) ptr->p is a+2; (ptr->p->i) is 3; pre-decrement makes it 2; a[2].z still "Bangalore" ⇒ prints " Bangalore".


Verification / Alternative check:
Instrument the code to print intermediate addresses and i values to verify pointer movement and decrement.


Why Other Options Are Wrong:
Option A: Fails to account for the ++ on z and the decremented index.
Option B/C: Mis-handle either the city names or the indices affected by pre-operators.


Common Pitfalls:
Forgetting that ++ on a pointer advances the string, and that -- applies to i inside the targeted struct, not the array index expression value alone.


Final Answer:
agpur, Bangalore, Bangalore

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion