Skip to content
Official PYQ · 2018

GATE CS 2018 Q29 — Programming in C

Explain with AI
#include<stdio.h>
void fun1(char* s1, char* s2){
    char* temp;
    temp = s1;
    s1 = s2;
    s2 = temp;
}
void fun2(char** s1, char** s2){
    char* temp;
    temp = *s1;
    *s1 = *s2;
    *s2 = temp;
}
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
View worked solution

Answer: A

To find the output of the program, let's trace the execution step-by-step:

1. Initialization in main()

Two character pointers are initialized to point to string literals:

  • str1 points to "Hi"
  • str2 points to "Bye"

2. Execution of fun1(str1, str2)

In C, arguments are passed by value. When we call fun1(str1, str2), copies of the pointers str1 and str2 are passed to the local parameters s1 and s2 of fun1.

void fun1(char* s1, char* s2){
    char* temp;
    temp = s1;
    s1 = s2;
    s2 = temp;
}

Inside fun1, the local pointers s1 and s2 are swapped, but this has no effect on the original pointers str1 and str2 in main().

Therefore, after fun1 returns:

  • str1 still points to "Hi"
  • str2 still points to "Bye"

The first print statement:
printf("%s %s", str1, str2); outputs Hi Bye.

3. Execution of fun2(&str1, &str2)

Here, the addresses of the pointers str1 and str2 are passed (pass-by-pointer). The parameters s1 and s2 in fun2 are of type char** (pointers to pointers).

void fun2(char** s1, char** s2){
    char* temp;
    temp = *s1;
    *s1 = *s2;
    *s2 = temp;
}

Inside fun2:

  • temp stores the value pointed to by s1 (which is the address of "Hi").
  • *s1 = *s2 updates the value of str1 in main() to point to "Bye".
  • *s2 = temp updates the value of str2 in main() to point to "Hi".

This successfully swaps the pointers str1 and str2 in main().

Therefore, after fun2 returns:

  • str1 points to "Bye"
  • str2 points to "Hi"

The second print statement:
printf("%s %s", str1, str2); outputs Bye Hi.

Conclusion

Combining the outputs of both print statements gives:
Hi Bye Bye Hi

Thus, the correct option is A.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions