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(&p);
printf("%d ", *p);
return 0;
}
void foo(int **p)
{
int j = 2;
*p = &j;
printf("%d ", **p);
}

 

  • A.2   2
  • B.2   97
  • C.Undefined behaviour
  • D.Segmentation fault/code crash

Answer: A

Correct answer: 2 2

Here the address of the pointer is passed, so *p = &j modifies the caller’s pointer itself and both prints give 2. That is how a function changes a pointer in its caller. Note that it is also a bug in the making: after foo returns, p in main points at j, whose lifetime has ended, so the second dereference is strictly undefined even though it prints 2 in practice.

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

Post your comment

Please log in or register to post a comment.