Understand how memory stack and function calls stack .
This code works, but it is wrong. He takes advantage of behavior that can not be guaranteed. By pure coincidence the variable str
of show()
was allocated in the same place of the variable str
of set()
. Because of this it works, but if you change this code a little, the coincidence does not occur and it will get a memory garbage. Technically it's already getting crap, but it's crap that's what I wanted, so everything seems ok.
When the code declares a local variable of a function this is placed in the first possible position of the stack. When you return to the calling function, the battery indication rewinds indicating that what is there is no longer needed and that any further allocation to the battery must occur at the previous point. This is useful because it makes memory allocations very fast. When you call the other function it needs to allocate memory. Where will you allocate? In the same place that I had allocated in the other function. So if you access this variable, get the value that was already there, because C does not erase memory on its own.
Just change this and you'll see problems:
int x = 0;
char vet[12];
printf("vet = '%s'\n", vet);
printf("x = %d", x);
See "working" on ideone and on CodingGround a>.