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);
}
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.
Please log in or register to report this question.