Consider the following code : #include void f1(char *x, char *y) { char *t; t…

2024

Consider the following code :
#include
void f1(char *x, char *y) {
char *t;
t = x;
x = y;
y = t;
}
void f2(char **x, char **y) {
char *t;
t = *x;
*x = *y;
*y = t;
}
int main() {
char *a = "ONE", *b = "TWO";
f1(a, b);
printf("%s %s", a, b);
f2(&a, &b);
printf("%s %s", a, b);
return 0;
}
What will be the output of the above code?

  1. A.

    ONE TWO TWO ONE

  2. B.

    TWO ONE ONE TWO

  3. C.

    ONE TWO ONE TWO

  4. D.

    TWO ONE TWO ONE

Attempted by 227 students.

Show answer & explanation

Correct answer: A

Explanation: step through the calls to see what changes.

  1. Initial state: a points to the string "ONE", and b points to the string "TWO".

  2. Call f1(a, b): the function parameters are copies of the pointers (pass-by-value). Swapping those local parameters changes only the local copies, not a and b in main. After f1 returns, a still points to "ONE" and b still points to "TWO".

  3. First printf prints: "ONE TWO".

  4. Call f2(&a, &b): the function receives pointers to the pointer variables. Inside f2, swapping *x and *y swaps the actual pointers in main, so a and b are exchanged.

  5. Second printf prints: "TWO ONE".

Final combined output printed to the console: ONE TWO TWO ONE

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Mppsc Assistant Professor