Q.Find and write the output of the following C++ program code: Note : Assume all required header files are already included in the program. void Alter(char *S1, char *S2) { char T; T=S1; S1=S2; S2=T; cout<<S1<<"&"<<S2<<end1; } void main() { char X[]="First", Y[]="Second"; Alter(X,Y); cout<<X<<""<<Y<<end1; }
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →The key idea is that Alter swaps the local pointer copies, not the original arrays. So inside the function, the swapped pointers are printed, but back in main, the original arrays X and Y remain unchanged. The output is Second&First followed by First*Second.
The trap here is subtle but classic: when you pass an array to a function in C++, what actually gets passed is a pointer to its first element. The function receives a copy of that pointer. Swapping the copies inside the function has no effect on the original arrays in main.
Let's trace it carefully.
-
What gets passed to
Alter?XandYare character arrays. When used as arguments, they "decay" to pointers:Xbecomes a pointer to the first'F', andYbecomes a pointer to the first'S'. The function receives copies of these pointer values — call themS1andS2. So initially,S1points to"First"andS2points to"Second". -
Inside
Alter, the swap happens on the copies.A temporary pointer
Tis used to swapS1andS2. After the swap:S1now points to"Second"S2now points to"First"
Then the function prints
S1 << "&" << S2, which outputsSecond&First. -
Back in
main, nothing has changed.The original arrays
XandYstill hold their original contents. The pointers that were swapped were just local copies insideAlter. Socout << X << "*" << YprintsFirst*Second. …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.