Question
Consider the following C program:
#include<stdio.h>
void fun1(char *s1, char *s2){
char *tmp;
tmp = s1;
s1 = s2;
s2 = tmp;
}
void fun2(char **s1, char **s2){
char *tmp;
tmp = *s1;
*s1 = *s2;
*s2 = tmp;
}
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
Official answer and solution
- Official answer
- A
- From
- Official GATE 2018 answer key
Solution
Contrast pass-by-value with pass-by-reference when manipulating pointer variables in C.
Trace fun1(str1, str2):
str1andstr2are pointer values passed by value.fun1receives copies of these pointers in local parameterss1ands2.- The swap operation inside
fun1only modifies the local copiess1ands2, leaving the originalstr1andstr2inmainunaffected. - Thus,
printf("%s %s ", str1, str2)prints:Hi Bye.
Trace fun2(&str1, &str2):
- The addresses
&str1and&str2are passed tofun2, which receives them aschar **. - Inside
fun2,*s1and*s2directly dereference the variablesstr1andstr2inmain, swapping the pointers themselves. - After
fun2,str1points to"Bye"andstr2points to"Hi". - Thus,
printf("%s %s", str1, str2)prints:Bye Hi.
Combining both outputs gives Hi Bye Bye Hi.
Final answer
A
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2018 Computer Science and Information Technology (CS)
- Question
- 39 of 65, printed as CS Q.29
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.