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?
- A.
ONE TWO TWO ONE
- B.
TWO ONE ONE TWO
- C.
ONE TWO ONE TWO
- D.
TWO ONE TWO ONE
Attempted by 227 students.
Show answer & explanation
Correct answer: A
Explanation: step through the calls to see what changes.
Initial state: a points to the string "ONE", and b points to the string "TWO".
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".
First printf prints: "ONE TWO".
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.
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.