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

Choose one option
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):

  • str1 and str2 are pointer values passed by value. fun1 receives copies of these pointers in local parameters s1 and s2.
  • The swap operation inside fun1 only modifies the local copies s1 and s2, leaving the original str1 and str2 in main unaffected.
  • Thus, printf("%s %s ", str1, str2) prints: Hi Bye .

Trace fun2(&str1, &str2):

  • The addresses &str1 and &str2 are passed to fun2, which receives them as char **.
  • Inside fun2, *s1 and *s2 directly dereference the variables str1 and str2 in main, swapping the pointers themselves.
  • After fun2, str1 points to "Bye" and str2 points 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.