edited by
9,584 views
37 votes
37 votes

What does the following program print?

#include<stdio.h>

void f(int *p, int *q) {
    p=q;
    *p=2;
}

int i=0, j=1;

int main() {
    f(&i, &j);
    printf("%d %d\n", i,j);
    return 0;
}
  1. $2 \ 2$
  2. $2 \ 1$
  3. $0 \ 1$
  4. $0 \ 2$
edited by

3 Answers

Best answer
53 votes
53 votes
 p=q; // now p and q are pointing to same address i.e. address of j
 *p=2;// value of j will be updated to 2

Hence, answer is (D) $0 2$

edited by
16 votes
16 votes

int  i=0, j=1;

The above statement declares and initializes two global variables.

void f(int *p ,int *q)
{
    % A %   p=q  // The address stored in pointer 'q' is assigned to pointer'p'
    % B %   *p=2  //The value at the address stored in pointer 'p' is set as 2. 
}

Now in the main function the function 'f' is called with the  address of variable 'i'   and 'j' as parameters.

Let us assume address of i=100 and address of j=200.

So the statement A in the definition of function f changes the value of the pointer 'p' from 100 to 200 as the pointer 'p' takes the address of pointer 'q'.

So after statement A the pointer 'p' also stores the address of j.

And in the statement B the value at address stored in the pointer 'p' is set to 2 this means the value of j is changed to 2.

Because of this the printf function in the main will print the value of i=0 and the value of j=2.

Therefore the output will be  0  2

Answer:

Related questions

26 votes
26 votes
2 answers
2