retagged by
569 views
1 votes
1 votes

Consider the following C program:-

#include <stdio.h>
void ubswap(int **a, int **b) {
    int* temp = *a;
    *a = *b;
    *b = temp;
}
int main() {
    int x = 1, y = 9;
    int* u = &x;
    int* v = &y;
    int** a = &u;
    int** b = &v;
    
    ubswap(a, b);
    return 0;
}

Which pair of variables in the main function are swapped immediately after the function call  $\textsf{“ubswap(a, b)”}$ and before $\text{“return 0”}?$

  1. $x$ and $y$
  2. $u$ and $v$
  3. $a$ and $b$
  4. None of the above
retagged by

1 Answer

7 votes
7 votes

See this is easy but tricky as well.

x is a variable which contains value 1 let say the address of x is 100 .

y is a variable which contains value 9 let say the address of y is 200 .

Now u and v are single pointer pointing to addresses 100 and 200 respectively. And assume the address of u is 300 and v is 400.

And a and b are double pointer pointing to addresses 300 and 400 respectively.And assume the address of a is 500 and b is 600.

Now ubswap() function is called which passes the two double pointers a and b.

Note: a is double pointer , so *a will be a single pointer.

int *temp = *a ;

This line mean temp is a single pointer which pointing to that location for which *a is pointing to .

And we know that *a or just say u , which is single pointer pointing to address location 100 which is nothing but address of x.

Similarly, *b or just say v , which is single pointer  pointing to address location 200 which is nothing but address of y.

So basically temp is pointing to x.

*a = *b ;

Means now *a or u starts pointing to y.

*b = temp;

Now *b or v is pointing to x;

And now return.

If we see carefully u and v pairs of variables got swapped as initially u was pointing to x but now it is pointing to y and v intially was pointing to y but now to x.

So, Option B is correct.

Hope, this helps.

 

Answer:

Related questions

529
views
1 answers
6 votes
GO Classes asked Jan 21
529 views
What will be the output of the following C program?#include<stdio.h> void main() { int i=6; for(--i; --i; i--) { printf("%d",i); } }$42$31$Infinite loopNone of these
481
views
1 answers
2 votes
GO Classes asked Jan 21
481 views
Consider the following two declarations for $\textsf{arr1}$ and $\textsf{arr2}:$int arr1[2][3]; int r1[3]; int r2[3]; int * arr2[2] = {r1, ... $(\operatorname{arr}2)=32$ bytes
702
views
3 answers
7 votes
GO Classes asked Jan 21
702 views
What will be the output of following program ?#include <stdio.h> int thefunction(int a) { static int b = 0; b++; a = a + b; return a; } int main() { int b = 0; int i; ... 3; i++) { b = b + thefunction(i); } printf("%d\n", b); return 0; }
510
views
1 answers
6 votes
GO Classes asked Jan 21
510 views
What will be the output of the following program?main() { int a[2][2] = { {1,2},{3,4} }; int(*p)[2][2]; p = &a; printf("%d", (*p)[0][0]); }$1$3$4$None of these