GATE / CS ARCHIVE

GATE CSE 2018 / QUESTION 29

Pointer swapping by value and address

Programming in C · Pointers & Memory · Full GATE CSE 2018 paper

GATE 2018, Q29 2 marks · MCQ
Report issue

Pointers & Memory

Question 29, GATE 2018: In C, str1="Hi", str2="Bye". fun1(char *s1,char *s2) swaps its local pointer variables using a temporary. fun2(char **s1,char **s2) swaps *s1 and *s2. main calls fun1(str1,str2), prints both strings, calls fun2(&str1,&str2), then prints both. Choices A Hi Bye Bye Hi; B Hi Bye Hi Bye; C Bye Hi Hi Bye; D Bye Hi Bye Hi.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Method

C passes arguments by value in both calls. In fun1 the copied values happen to be addresses of characters, so replacing those local copies cannot replace main’s variables. In fun2 the copied values are addresses of main’s pointer variables; dereferencing them selects those actual variables, which the assignments can modify. Neither routine edits the string literals. This distinction is between swapping pointed-to pointers and swapping local pointer copies, not between two language-level parameter-passing modes.

Solution

fun1 swaps only local copies of the pointer values, leaving main’s strings unchanged: Hi Bye. fun2 receives their addresses and swaps the actual pointer variables, so the second output is Bye Hi. The whole output is Hi Bye Bye Hi, A.

Original paper, page 12 · Answer key