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

Discussion

What is the output of this C code?

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

The postfix ++ yields the value the pointer had before the increment, so foo receives the original address of i and prints 10. The increment happens to p in main, which afterwards points one int past i - harmless here since it is never dereferenced. Prefix ++p would have passed the advanced pointer and the behaviour would then have been undefined.

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

Post your comment

Please log in or register to post a comment.