Which one of the choices given below would be printed when the following…

2006

Which one of the choices given below would be printed when the following program is executed ?

 #include <stdio.h>
struct test {
               int i;
               char *c;
}st[] = {5, "become", 4, "better", 6, "jungle", 8, "ancestor", 7, "brother"};
main ()
{ 
    struct test *p = st;
    p += 1;
    ++p -> c;
    printf("%s,", p++ -> c);
    printf("%c,", *++p -> c);
    printf("%d,", p[0].i);
    printf("%s \\n", p -> c);
} 

  1. A.

    jungle, n, 8, nclastor

  2. B.

    etter, u, 6, ungle

  3. C.

    cetter, k, 6, jungle

  4. D.

    etter, u, 8, ncestor

Attempted by 116 students.

Show answer & explanation

Correct answer: B

Key insight: trace the struct pointer p and the char* field (c); p++ and ++ applied to p->c move different things.

  • Step 1: p = st; p += 1 makes p point to the second element: i = 4, c = "better".

  • Step 2: ++p->c increments the char* inside that struct. c moves from "better" to "etter" (skips 'b').

  • Step 3: printf("%s", p++->c) prints the current p->c ("etter"). The p++ returns the old p for the ->c access, then p increments to the next struct (i = 6, c = "jungle").

  • Step 4: printf("%c", *++p->c) operates on the current p (now the "jungle" element). ++p->c advances that c from "jungle" to "ungle", and * returns the first character 'u'.

  • Step 5: printf("%d", p[0].i) prints the current struct's integer, which is 6.

  • Step 6: printf("%s\n", p->c) prints the current c, which is now "ungle".

Program output: etter,u,6,ungle

This matches the choice that reads "etter, u, 6, ungle".

Explore the full course: Gate Guidance By Sanchit Sir