edited by
14,954 views
46 votes
46 votes
#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:

  1. $\text{Hi Bye Bye Hi}$
  2. $\text{Hi Bye Hi Bye}$
  3. $\text{Bye Hi Hi Bye}$
  4. $\text{Bye Hi Bye Hi}$
edited by

5 Answers

Best answer
41 votes
41 votes
func1(char* s1, char* s2){
    char* temp;
    temp = s1;
    s1 = s2;
    s2 = temp;
}

Everything is local here. So, once function completes its execution all modification go in vain.

func2(char** s1, char** s2){
    char* temp
    temp = *s1
    *s1 = *s2
    *s2 = temp
}

This will retain modification and swap pointers of string.
So output would be Hi Bye Bye Hi

Correct Answer: $A$

edited by
8 votes
8 votes

The first call to the function 'func1(str1,str2);' is Call by Value. Hence, any change in the formal parameters are NOT reflected in actual parameters. Hence, str1 points at "hi" and str2 points at "bye".

The second call to the function 'func2(&str1,&str2);' is Call by Reference. Hence, any change in the formal parameters are reflected in actual parameters. Hence, str1 now points at "bye" and str2 points at "hi".

Hence, answer is hi byebye hi ....

0 votes
0 votes
The first call to the function ‘func1(str1, str2);’ is call by value.
Hence, any change in the formal parameters are NOT reflected in actual parameters.
Hence, str1 points at “hi” and str2 points at “bye”.
The second call to the function ‘func2(&str1, &str2);’ is call by reference.
Hence, any change in formal parameters are reflected in actual parameters.
Hence, str1 now points at “bye” and str2 points at “hi”.

Hence answer is “hi bye bye hi”.
Answer:

Related questions

42 votes
42 votes
9 answers
3