Consider the following C program: #include <stdio.h> typedef struct { char *a;…

2004

Consider the following C program:

#include <stdio.h>
typedef struct 
{
    char *a;
    char *b;
} t;
void f1(t s);
void f2(t *p);
main()
{
    static t s = {"A", "B"};
    printf ("%s %s\n", s.a, s.b);
    f1(s);
    printf ("%s %s\n", s.a, s.b);
    f2(&s);
}
void f1(t s)
{
    s.a = "U";
    s.b = "V";
    printf ("%s %s\n", s.a, s.b);
    return;
}
void f2(t *p)
{
    p -> a  = "V";
    p -> b = "W";
    printf("%s %s\n", p -> a, p -> b);
    return;
}

What is the output generated by the program ?

  1. A.

    A B U V V W V W

  2. B.

    A B U V A B V W

  3. C.

    A B U V U V V W

  4. D.

    A B U V V W U V

Attempted by 40 students.

Show answer & explanation

Correct answer: B

Reasoning: understand how pass-by-value and pass-by-pointer affect the struct.

  • Initially, main initializes the struct fields to "A" and "B" and prints: A B.

  • f1 receives the struct by value (a copy). f1 assigns the copy's fields to "U" and "V" and prints: U V. These changes affect only the copy inside f1.

  • Back in main, the original struct is unchanged, so the next print outputs: A B.

  • f2 receives a pointer to the struct and modifies the original fields to "V" and "W", then prints: V W.

Final output (each line is a separate printf):

  1. A B

  2. U V

  3. A B

  4. V W

Explore the full course: Gate Guidance By Sanchit Sir