I'm trying to understand more about how the stack internally works.
I have a decent understanding of what the stack is, what the heap is and how they compare. At this point, I'm not interested in how the stack is used when invoking another function and then returning from that function.
I want to know how local variables are stored on the stack and how they are retrieved.
So the stack is an array of bytes. There must also be a value stored somewhere that keeps track of the current position on the stack. I don't know where that is stored or how it's called, but lets call it POS for now.
I start clean with an empty stack and POS=0.
I declare variable A as a 16 bit integer and assign the value 5. Now the first 2 bytes of the stack are occupied, they hold the value 5 and POS=2.
I declare variable B as an array of length A of 16 bit integers. Now the next 10 bytes of the stack are occupied as well, they hold an array of length 5, where each element in the array has a length 2, and POS=12.
I declare variable C as a 32 bit integer and assign the value 0. Now the next 4 bytes of the stack are occupied too and POS=16.
I declare variable D as a 16 bit integer and now POS=18.
At this point, I want to output the value of C. When we look at the assembler instructions, how does the program know which 4 bytes to read from the stack? How does it know that C starts at position 12?