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

Discussion

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

Here the address is held in a pointer variable, so p++ is legal. It is a post-increment, so the value passed to foo is the original value of p - the address of i - and p is incremented afterwards.

foo therefore dereferences a pointer to i and prints 10. The increment of p has no effect on the output, and since p is never used again the value it now holds - one past i - is harmless.

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

Post your comment

Please log in or register to post a comment.