Project ForgeSign up free
Programming in C
Programming Fundamentals
GATE 2018
Hard

Consider the following C program:

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

  • Hi Bye Bye Hi
  • BHi Bye Hi Bye
  • CBye Hi Hi Bye
  • DBye Hi Bye Hi

Explanation

fun1 receives copies of the pointers (pass-by-value) and swaps only its LOCAL copies — str1, str2 in main are unaffected, so the first printf shows 'Hi Bye '. fun2 receives the ADDRESSES of str1, str2 and swaps through the double-pointer dereference, which DOES change the actual variables in main — so after fun2, str1='Bye', str2='Hi', and the second printf shows 'Bye Hi'. Total output: 'Hi Bye Bye Hi'.

Source: GATE CS 2018 (2018)

This question is part of a 15-day revision cycle — sign in and Project Forge will bring it back the day before you'd forget it.

Start revising free