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

Discussion

What is the output of this C code?

int main()
{
int i = 97, *p = &i;
foo(&i);
printf("%d ", *p);
}
void foo(int *p)
{
int j = 2;
p = &j;
printf("%d ", *p);
}

 

  • A.2   97
  • B.2   2
  • C.Compile time error
  • D.Segmentation fault/code crash

Answer: A

Correct answer: 2 97

The parameter p inside foo is a local copy of the pointer, so p = &j redirects only that copy. It prints 2. Back in main the original pointer is untouched and still points at i, so the second print gives 97. C passes everything by value, pointers included - which is exactly why the next question passes the address of the pointer instead.

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

Post your comment

Please log in or register to post a comment.