in Programming in C
763 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);
}
in Programming in C
763 views

1 Answer

6 votes
6 votes
Best answer

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

7 Comments

If the function argument dint have constant, then what would be the output
0
0
Nothing will change.

When it is const. pointer and we try to change the address to which $a'$ points to,  it will report an error saying a' is read only and we cann't write it.
1
1
If it was

void foo(int *a) what would happen

and what if its void foo(int const*a)
0
0

In this case $a$ inside foo() is a pointer to int. So  print(**a); will give error.

But try out what happens when foo is changed as $\Rightarrow$

void foo(int *const a) {  
  int j = 210;  
  *a = &j;  
  printf("%d ", *a); 
}
0
0
It gives garbage value and for the print in main() it prints 120,cannot understand the trace of the program

can u explain it the way u have explained above for this code tooo
0
0

Yr it's easy. Just use pen and paper to trace the program. Don't use compiler for find the output type questions.

Both printfs in main() print $120$ because a in main() still points to i.  
And printf in foo() prints address of variable j. (It's not garbage value ). See we have assigned *a = &j; before printing.

1
1
thank you:)
1
1

Related questions