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

Discussion

What will be the output of the following 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

The pointer is passed by value, so foo receives a copy. Assigning p = &j inside foo changes only that copy, and the print there shows 2.

Back in main, the original p still points to i, so the second print shows 97. This is the fundamental point about pointer arguments: passing a pointer lets a function modify what it points to, but not the caller's pointer itself. Changing the caller's pointer requires a pointer to pointer.

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

Post your comment

Please log in or register to post a comment.