Machine-translated by Google. Questions are authored in English.
Top

Discussion

What is the output of the following program ?

#include<stdio.h>
void f(int *p, int *q) {
    p=q;
    *p=2;
}
int i=0, j=1;
int main(void){
    f(&i, &j);
    printf("%d %d\n", i, j);
    }

  • A.2 2
  • B.2 1
  • C.0 1
  • D.0 2

Answer: D

The program prints 0 2.

C passes arguments by value, so p and q are local copies of the addresses &i and &j. Walk through f:

  1. p=q; changes only the local copy p, which now holds &j. The variable i is untouched.
  2. *p=2; writes 2 through p, that is into j.

Back in main, i is still 0 and j is now 2, so printf prints 0 2. '2 1' is what you would get if *p=2 still wrote to i; '2 2' assumes p=q changed main's pointer; '0 1' ignores the write through p altogether.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.