, this question is a bit retarded at first glance (sorry ha), but it's interesting to take a closer look.
first of all, as mentioned above, ptr and pptr are the addresses of local variables during two function calls, and it is certain that the addresses assigned to the two calls to the same local variable may not be the same.
but! Two consecutive calls to the same function, the allocation of stack frames are likely to be the same, the reason is very simple, the application stack is usually allocated continuously, gradually growing down with layer by layer of calls. So immediately after the previous get function is called, it should be called again, and if nothing happens, the stack frames should be the same. This point has also been repeated many times during the debugging of the subject.
so why do two pointers with the same address print different values? The answer is "your two pointers are external public addresses, who stipulates that they must be the same!"
look carefully, who is most likely to change the value on this address? Haha, sorry, although well hidden but still found, that is printf!
when printing for the first time, the value of ptr is taken out before the stack frame of printf is allocated, so printf can print out 1, but as printf runs, it overwrites the value on that address, and then it is no longer the original value.
the subject can exchange two print statements, and you will find that the first print is always right, and the second time is wrong, regardless of whether the print is ptr or pptr.
so, if you understand the principle, you will know why you can't use it this way.
ptr
and pptr
actually refer to the address of a
in the function get
. a
is a local variable within the function, and the stack will be reassigned each time, and the address must be different.
the same function has been run twice. How can the address of the variable in it be the same? the address must be the same as the name of the variable.
the pptr and ptr in the main function both point to the address of the local variable in the function get function, while the local variable in get is released at the end of the function, that is, the pointer in the main points to the released address, and the operation behavior of taking the value in it is undefined. The result is a random
running the same function over and over again