Consider the following C program: #include<stdio.h> void fun1(char *s1, char…

2018

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

Attempted by 212 students.

Show answer & explanation

Correct answer: A

Short answer: Hi Bye Bye Hi

Explanation:

  • Initial state in main: str1 points to the string "Hi" and str2 points to the string "Bye".

  • Call to the first function with fun1(str1, str2): fun1 receives parameters of type char* (copies of the pointers). Swapping s1 and s2 inside fun1 swaps only these local copies and does not change str1 and str2 in main.

  • After fun1 returns, main still has str1 -> "Hi" and str2 -> "Bye", so the first printf prints: Hi Bye

  • Call to the second function with fun2(&str1, &str2): fun2 receives parameters of type char** (addresses of the pointers). By using *s1 and *s2 it updates the actual pointers in main, so this call swaps str1 and str2 in main.

  • After fun2 returns, main has str1 -> "Bye" and str2 -> "Hi", so the second printf prints: Bye Hi

  • Combining both prints (first and second) yields the final output: Hi Bye Bye Hi

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir