The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
+18 votes
1.7k views

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$
asked in Programming by Veteran (106k points)
edited by | 1.7k views
0
Why would someone pass address of global variable to a function??

2 Answers

+28 votes
Best answer
 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

answered by Boss (41k points)
edited by
+5 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

answered by (391 points)
0
I have a doubt. In function "f" no value is being returned,then also value of J will get changed?
0
@Divyanka, we are sending address of the variable and modifying the value at that address which will definitely change the value of the variable.
0
ok. thank u
Answer:

Related questions



Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

42,598 questions
48,599 answers
155,642 comments
63,709 users