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