Consider the following code: #include void f1(char *x, char *y) { char *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 218 students.
Show answer & explanation
Correct answer: A
Answer: ONE TWO TWO ONE
Explanation:
Initial state: a points to the string "ONE", b points to the string "TWO".
Call to the first function (f1): it receives parameters of type char* by value. Swapping x and y inside f1 only swaps the local copies of the pointers; it does not modify the caller variables a and b. Therefore the first printf prints "ONE TWO".
Call to the second function (f2): it receives char** (pointers to the caller pointers) and swaps *x and *y, which swaps the caller pointers a and b. After this call the variables are swapped, so the second printf prints "TWO ONE".
Combining both prints (first printf then second printf) yields: "ONE TWO TWO ONE".