1,655 views
3 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 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
Position:
Show:

Related questions

2 2 votes
4 4 answers
1.7k
1.7k views
Anil Khatri asked Sep 9, 2016
1,735 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 0 votes
0 0 answers
729
729 views
Hira Thakur asked Nov 18, 2017
729 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; ...
1 1 vote
2 answers 2 answers
1.2k
1.2k views
radha gogia asked Jul 25, 2015
1,212 views
#include<stdio.h int main() { int x=3; int const *ptr =&x; printf("%d",++x); printf("\n %d",++*ptr); return 0; } I am unable to get that when x is a variable not a consta...
2 2 votes
3 answers 3 answers
2.1k
2.1k views
Nitesh Choudhary asked Apr 20, 2017
2,136 views
what is difference between "int * const ptr=&i" and const int *ptr;;