762 views
3 votes
3 votes
The output of below code is_______________.

int main()
{
   int i = 120;
   int *a = &i;
   foo(&a);
   printf("%d ", *a);
   printf("%d ", *a);
}
void foo(int **const a)
{
  int j = 210;
  *a = &j;
  printf("%d ", **a);
}

1 Answer

Best answer
6 votes
6 votes

After the execution of first two statements in main() function, the variables in memory are stored like $\Rightarrow $

Now address of $a$ is passed to function foo() where there is a local variable $a$ that stores the address of pointer passed. (Lets say this local variable as $a'$ )

So, when foo() executes its first two statements memory layout is like :: 

So, printf() inside foo() prints $\color{blue}{210}$.

After foo() completes its activation record is removed from stack. So, only variable $i$ and pointer $a$ remain in memory, where $a$ points to an address that is not available now.

Now what last two printfs will print depends on how compiler behaves when it removes activation record. If it replaces memory location $400$ (variable j)  with $0$, it will print $0$ or if it retains previous value that is $210$, it will print $210$. 

selected by

Related questions

1 votes
1 votes
2 answers
1
Anil Khatri asked Sep 9, 2016
974 views
What will be the output of the program?#include<stdio.h int main() { const c = -11; const int d = 34; printf("%d, %d\n", c, d); return 0; } A. Error B. -1...
0 votes
0 votes
0 answers
2
Hira Thakur asked Nov 18, 2017
353 views
The output of below code is_______________. int main() { int i = 120; int *a = &i; foo(&a); printf("%d ", *a); printf("%d ", *a); } void foo(int const a) { int j = 210; ...
2 votes
2 votes
3 answers
4