In C, swapping function parameters passed by value (pointers to string literals): what prints?
#include
void swap(char *, char *);
int main()
{
char *pstr[2] = {"Hello", "CuriousTab"};
swap(pstr[0], pstr[1]);
printf("%s
%s", pstr[0], pstr[1]);
return 0;
}
void swap(char *t1, char *t2)
{
char *t;
t = t1;
t1 = t2;
t2 = t;
}
-
ACuriousTab Hello
-
BAddress of "Hello" and "CuriousTab"
-
CHello CuriousTab
-
DIello HndiaCURIOUSTAB
-
EUndefined behavior at runtime
Answer
Correct Answer: Hello CuriousTab
Explanation
Introduction / Context:This assesses understanding of parameter passing in C. Even when pointers are involved, C passes arguments by value. Swapping local parameter copies does not change the caller's pointers.
Given Data / Assumptions:
- pstr[0] → "Hello", pstr[1] → "CuriousTab".
- swap receives copies of these two pointer values.
- Inside swap, t1 and t2 are local; reassigning them does not affect the caller's array entries.
Concept / Approach:To modify the caller's pointers, swap must receive addresses of the pointers (i.e., char **), or you must pass &pstr[0] and &pstr[1]. As written, only the local copies move around, and the caller remains unchanged.
Step-by-Step Solution:Before call: pstr[0] = "Hello"; pstr[1] = "CuriousTab".swap(t1, t2): t1 and t2 are copies; t1 = t2; t2 = t swaps locals only.After return: pstr unchanged.printf prints original order on two lines: "Hello" then "CuriousTab".
Verification / Alternative check:Change swap signature to void swap(char **t1, char *t2) and call swap(&pstr[0], &pstr[1]). Then dereference inside to swap caller's entries.
Why Other Options Are Wrong:(a) would occur only if the caller's pointers were swapped. (b) is not what printf with %s prints. (d) is unrelated text. (e) There is nothing undefined here.
Common Pitfalls:Assuming “pass by reference” because pointers are involved; forgetting that %s expects a char to a null-terminated string.
Final Answer:Hello CuriousTab