in Programming in C
825 views
2 votes
2 votes

Can anyone confirm this I think output must be 2 97 but given ans is 2 2. ?

in Programming in C
825 views

4 Comments

@saxena0612 No any errors in this code.

Pointer is defined already in main.

In 2nd print it will print printf of main() which is directly pointing to value of i. but how this code got value as 2 instead of 97??
1
1
This is a nice trick question,actually the catch is when you are passing to foo you are sending address of p and in the main function the definition of p remains the same,its a single pointer, when you are changing the single pointer to p in foo itself its value gets changed.So,it will print 2 and 2.If you have doubts better debug this code.
0
0

it is the case of dangling pointer .....even address of j is hold by p but it is not available in memory.....? how 

does  compiler handle such cases...??any one please...

0
0

1 Answer

2 votes
2 votes

Finally I understood the tricky concept in this . Thanks to @Surajit.

Here's is visual explanation about this snippet,

4 Comments

it is compiler dependent, it depends on how compiler deals with local variable(in this case j), once the activation record of function is popped off(in this case foo())
0
0
edited by
Hmm, That's also correct! If function is popped off j, then what will be the behavior of pointer p of main? It will be a dangling pointer or simply again points to local variable ? (This doubt occurred because value of address in p (main) is already changed)
0
0
This function may give run time error because of dangling pointer.
2
2
correct can happen...if we throw out j or collect its memory whenever its goes out of scope from foo(),it can point to some void location....but does that occur automatically in any C compiler?I have no knowledge.Certainly an ill framed question..
0
0

Related questions