The GATE Grind

GATE 2018 CS – Question 39

Programming and Data Structures · Programming in C · 2 marks · Multiple choice

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

  1. Hi Bye Bye Hi
  2. Hi Bye Hi Bye
  3. Bye Hi Hi Bye
  4. Bye Hi Bye Hi

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: (A) Hi Bye Bye Hi

Explanation

`fun1` swaps only its local copies of the pointers, so `str1` and `str2` are unchanged and it prints `Hi Bye`. `fun2` swaps the actual pointers through their addresses, so it then prints `Bye Hi`.