#include<stdio.h>
void fun1(char* s1, char* s2){
char* temp;
temp = s1;
s1 = s2;
s2 = temp;
}
void fun2(char** s1, char** s2){
char* temp;
temp = *s1;
*s1 = *s2;
*s2 = temp;
}
int main(){
char *str1="Hi", *str2 = "Bye";
fun1(str1, str2); printf("%s %s", str1, str2);
fun2(&str1, &str2); printf("%s %s", str1, str2);
return 0;
}
The output of the program above is:
View worked solution
Answer: A
To find the output of the program, let's trace the execution step-by-step:
1. Initialization in main()
Two character pointers are initialized to point to string literals:
str1points to"Hi"str2points to"Bye"
2. Execution of fun1(str1, str2)
In C, arguments are passed by value. When we call fun1(str1, str2), copies of the pointers str1 and str2 are passed to the local parameters s1 and s2 of fun1.
void fun1(char* s1, char* s2){
char* temp;
temp = s1;
s1 = s2;
s2 = temp;
}
Inside fun1, the local pointers s1 and s2 are swapped, but this has no effect on the original pointers str1 and str2 in main().
Therefore, after fun1 returns:
str1still points to"Hi"str2still points to"Bye"
The first print statement:
printf("%s %s", str1, str2); outputs Hi Bye.
3. Execution of fun2(&str1, &str2)
Here, the addresses of the pointers str1 and str2 are passed (pass-by-pointer). The parameters s1 and s2 in fun2 are of type char** (pointers to pointers).
void fun2(char** s1, char** s2){
char* temp;
temp = *s1;
*s1 = *s2;
*s2 = temp;
}
Inside fun2:
tempstores the value pointed to bys1(which is the address of"Hi").*s1 = *s2updates the value ofstr1inmain()to point to"Bye".*s2 = tempupdates the value ofstr2inmain()to point to"Hi".
This successfully swaps the pointers str1 and str2 in main().
Therefore, after fun2 returns:
str1points to"Bye"str2points to"Hi"
The second print statement:
printf("%s %s", str1, str2); outputs Bye Hi.
Conclusion
Combining the outputs of both print statements gives:
Hi Bye Bye Hi
Thus, the correct option is A.
Free practice · Your answers on this page are not saved.
