Machine-translated by Google. Questions are authored in English.
Top

Discussion

Consider the following C program:

#include\(\lt\)stdio.h\(\gt\)

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

  • A.Hi Bye Bye Hi
  • B.Hi Bye Hi Bye
  • C.Bye Hi Hi Bye
  • D.Bye Hi Bye Hi

Answer: A

The program prints Hi Bye Bye Hi.

fun1 receives copies of the two pointers. It swaps its own copies, but str1 and str2 in main are unchanged, so the first printf prints 'Hi Bye '.

fun2 receives the addresses of str1 and str2. Writing through *s1 and *s2 swaps the pointers in main itself, so str1 now points to "Bye" and str2 to "Hi", and the second printf prints 'Bye Hi'.

'Hi Bye Hi Bye' assumes neither function swaps anything. The options starting 'Bye Hi' assume fun1's swap reaches main, which C's pass-by-value rules out.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.