IAE Academy

GATE 2018 CS Q.29: solution and answer

GATE 2018 · CSQ.29 · 2 marks · MCQ

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. (A)

    Hi Bye Bye Hi

  2. (B)

    Hi Bye Hi Bye

  3. (C)

    Bye Hi Hi Bye

  4. (D)

    Bye Hi Bye Hi

See the question in the paper

Answer and solution

ANSWER

The output is "Hi Bye Bye Hi" — option (A).

Official answer: ASource: Official answer key, GATE 2018 CS (IIT Guwahati)

  1. main: str1->Hi, str2->Bye.

  2. fun1 is pass-by-value on pointers: swapping local s1/s2 does not change main's str1/str2.

  3. First printf("%s %s ", str1, str2) outputs "Hi Bye " (trailing space in format).

  4. fun2(&str1,&str2) receives addresses, so *s1/*s2 alias str1/str2; the swap via tmp genuinely swaps str1 and str2.

  5. After fun2: str1->Bye, str2->Hi.

  6. Second printf("%s %s", str1, str2) outputs "Bye Hi" (no trailing space).

  7. Concatenated output: "Hi Bye "+"Bye Hi" = "Hi Bye Bye Hi" = option (A).

KEY IDEA

fun1 takes pointers by value, so swapping its local pointer copies does not affect main's variables; fun2 takes pointer-to-pointer, so *s1/*s2 alias str1/str2 and the swap is real.

WATCH OUT FOR

Thinking fun1 also swaps str1/str2 in main because its parameters are pointers — confusing "pointer parameter" with "reference parameter". Only fun2 (char **) can modify the caller's pointer variables.

From the GATE 2018 CS paper. Every question of this paper · Download the full paper · All 7 Functions & scope questions, with notes

More Functions & scope questions