In C, swapping two pointers to string literals inside an array: what exactly does this program print?
#include
int main()
{
char *names[] = { "Suresh", "Siva", "Sona", "Baiju", "Ritu"};
int i;
char *t;
t = names[3];
names[3] = names[4];
names[4] = t;
for (i = 0; i <= 4; i++)
printf("%s,", names[i]);
return 0;
}
Choose the correct comma-separated order.
-
ASuresh, Siva, Sona, Baiju, Ritu
-
BSuresh, Siva, Sona, Ritu, Baiju
-
CSuresh, Siva, Baiju, Sona, Ritu
-
DSuresh, Siva, Ritu, Sona, Baiju
-
ENone of the above
Answer
Correct Answer: Suresh, Siva, Sona, Ritu, Baiju
Explanation
Introduction / Context:This question checks pointer swapping in an array of pointers to string literals. Instead of moving characters, the code swaps pointers, which is efficient and changes the printed order of names without copying strings.
Given Data / Assumptions:
- names is an array of 5 pointers to constant string literals.
- Indices: names[0]=Suresh, [1]=Siva, [2]=Sona, [3]=Baiju, [4]=Ritu.
- We swap names[3] and names[4] using a temporary pointer t.
- The loop prints each name followed by a comma, in index order 0..4.
Concept / Approach:Swapping pointers changes which strings are referenced at positions 3 and 4. Pointer swapping does not modify the literals themselves; it only reassigns which address is stored in each array slot.
Step-by-Step Solution:Before swap: [Suresh, Siva, Sona, Baiju, Ritu].t = names[3] makes t point to "Baiju".names[3] = names[4] assigns "Ritu" to index 3.names[4] = t assigns "Baiju" to index 4.Printing 0..4 after swap yields: Suresh, Siva, Sona, Ritu, Baiju,
Verification / Alternative check:Add printf calls before and after the swap to confirm index contents changed as expected. Since these are literals, no memory copying occurs.
Why Other Options Are Wrong:Original order (option a) ignores the swap.The other permutations do not reflect swapping exactly the last two entries.
Common Pitfalls:Confusing character arrays with pointer arrays; attempting to free string literals; thinking swap copies data rather than pointer values.
Final Answer:Suresh, Siva, Sona, Ritu, Baiju