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

Discussion

What is the output of this C code?

#include <stdio.h>
    void foo(int*);
    int main()
    {
        int i = 10, *p = &i;
        foo(p++);
    }
    void foo(int *p)
    {
        printf("%d\n", *p);
    }

 

  • A.10
  • B.Some garbage value
  • C.Compile time error
  • D.Segmentation fault

Answer: A

Correct answer: 10

p++ is a post-increment, so the value passed to foo is p as it was - the address of i - and only afterwards does p advance.

foo therefore dereferences a valid pointer and prints 10. The increment leaves p pointing one past i, which is never used, so no harm follows. Had the pre-increment ++p been written, the pointer passed would have been one past the object and the dereference undefined.

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

Post your comment

Please log in or register to post a comment.