Quick Print – Computer Sir Ki Class

Login


Lost your password?

Don't have an account ?
Register (It's FREE) ×
  


Shop
siteicon
Solved Problem Solved Problem#CPP#6953

Problem Statement - Function arguments as pointer reference – Output writing

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<<endl;
}
void main()
{
  charX[]="First", Y[]="Second";
  Alter(X,Y);
  cout<<X<<"*"<<Y<<endl;
}

 

Solution

		 

Run Output

Second&First
First*Second

Second&First
First*Second

This is how it works:
char X[]=”First”, Y[]=”Second”; //Two character array are initialised with First and Second
Alter(X,Y);                                      //This transfers location of first member of X and first member of Y

void Alter(char *S1, char *S2)    //Here it enters function using pointer types as they are just location addresses
{
char *T;   //A char pointer type is declared
T=S1; S1=S2; S2=T; //This is typical pointer swapping technique using temporary pointer T
cout<<S1<<“&”<<S2<<endl; //Here Second&First is displayed as values are read from alternative locations due to swapping
S1 is actually being read from where S2 was there previously and vice-versa. remember content actually remains at their original
positions only. With no instruction content has been moved or copied.
}

cout<<X<<“*”<<Y<<endl; 
This is output line back in main routine. Since the actual content is at there respective positions only so This will display
First*Second   only