Skip to content
GATEiit

GATE CSE 2018 Q39: Swapping string pointers by value and by address in C

Syllabus topic: Programming in C

Question

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

Try it: multiple choice: exactly one correct option

Select one option
Wrong answer costs 2/3 mark in GATE.
Show answer and explanation

Answer: A (official GATE 2018 final answer key)

Concept used: C passes arguments by value: swapping pointer copies inside a function has no effect on the caller, but swapping through pointers to the pointers does.

Concept notes

Loading notes…

First step: Check whether fun1 and fun2 change the variables str1 and str2 of main or only local copies.

Full step-by-step solution

Loading…

Answer from the official final answer key. Found a mistake? Use Report issue and we will fix it.

More questions on Programming in C

Every PYQ on this topic →

Share this question

WhatsAppDownload image

Source: official GATE 2018 CS question paper and final answer key, organised by IIT Guwahati. Question paper · Answer key