Typedef in C MCQs Exercise II


Ques 1 Typedef


What is the output of the following code?
#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?

  a)
A B
U V
V W
V W

  b)
A B
U V
A B
V W

  c)
A B
U V
U V
V W

  d)
A B
U V
V W
U V


b is the correct option

main function,
Initializes a static t s = {"A", "B"}, creating a local static struct variable in main.
Prints the initial values of s.a and s.b: A B.
Calls f1(s), passing a copy of s by value.
Prints the values of s.a and s.b again (these values haven't changed): A B.
Calls f2(&s), passing the address of s (pointer to s).
f1 function:
Receives a copy of s (pass-by-value).
Changes the copy's a and b members to "U" and "V", but this only affects the copy within f1.
Prints the modified values inside f1: U V.
f2 function:
Receives the address of s (pointer to s).
Changes the original struct's a and b members through the pointer, modifying the actual s variable in main.
Prints the modified values inside f2: V W.
Key Points:
In f1, changes to the passed copy do not affect the original s in main.
In f2, changes made through the pointer directly modify the original s in main.
The final output reflects the modifications made in f2.