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
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.
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development