This is what's going under the hood when using pointer (Note that pointer is just like what the name implies, something like a finger pointing to something).
Let's break down your codes and understand it bit by bit.
In your main function, you declared a character pointer *c
char *c;
Then you did this:
c = func();
which tells the c pointer to point to whatever this func() is pointing to.
Let's look at your function
char* func()
{
char *ptr = "OK";
return ptr;
}
The first line, again, declare a character pointer ptr, and assigned "OK" to that address (Note: pointer just points to some memory address). So now, that address contains the string "OK" (or more precisely, an array of char).
Then you return ptr, which is the address of where "OK" is located at. Note that because ptr is declared in func(), it is a local variable. Hence, once return, it is removed from the stack (poof! Gone).
However, because in your main():
c = func();
The variable c is pointing to the address of where "OK" is stored. Hence, even though the variable ptr no longer exist, the variable c knows where it is, and can still access "OK".
To answer your question:
- ptr is stored at stack
- and ptr is pop off from the stack when you exit the func()