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

Discussion

What is the output of this C code?

#include <stdio.h>
    int main()
    {
        int i = 97, *p = &i;
        foo(&i);
        printf("%d ", *p);
    }
    void foo(int *p)
    {
        int j = 2;
        p = &j;
        printf("%d ", *p);
    }

 

  • A.2 97
  • B.2 2
  • C.Compile time error
  • D.Segmentation fault/code crash

Answer: A

Correct answer: 2 97

foo receives a copy of the pointer. Assigning p = &j inside it changes only that copy, so foo prints 2 and the caller's pointer is untouched.

Back in main, p still points at i, and 97 is printed. C passes everything by value, pointers included: to let a function change the caller's pointer it must be given the address of that pointer, which is what the companion question does with int **.

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

Post your comment

Please log in or register to post a comment.