The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
+17 votes

What does the following program print?


void f(int *p, int *q) {

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 (115k points)
edited by | 2k views
Why would someone pass address of global variable to a function??

2 Answers

+29 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 (42.6k 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)
I have a doubt. In function "f" no value is being returned,then also value of J will get changed?
@Divyanka, we are sending address of the variable and modifying the value at that address which will definitely change the value of the variable.
ok. thank u

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
47,931 questions
52,335 answers
67,817 users