Stack Access Clarification Question

TLDR: Can you copy the value/address of a variable in the middle of the stack if its not removing the element?

I've looked at several different online sources explaining the stack and the heap in regards to C/C++. I've also tried googling my question and searching these forums to no avail (although it's possible I just did not type in the correct phrase into the forum search engine).

Every source I've read has said that the stack is first in last out FILO. Now, the way this is described leaves me confused regarding a single issue. I'm extremely certain that FILO implies that you can only ADD and REMOVE items from the top of the stack. However, I cannot find any clarification regarding reading or copying values that are not on the top of the stack (not adding or removing).

That is, for example, if I want to read the value of some variable from the middle of the stack and compare it to some other variable in my program or if I want to copy its value/address to some other variable/pointer does that mean the entire stack has to unwind? Like, does it have to make a new stack, and pop off everything from the top of the current one and add it to the second to get to the item I want to look at or copy, and then place everything back on the first stack and delete the second stack?

If so, Is that really the most efficient way to store memory that is in use?

If not, then I assume you can read and copy mid-stack elements it's just that you can only add and delete the top element?

Any clarification on this issue would be very much appreciated and help my understanding of how memory allocation and access works in C++.

Thank you very much for your time and your consideration. I hope you have a great day/night.

Sincerely,

Generic
Most stack implementations don't provide a way for you to access elements that are not at the 'top' of the stack. If you're using a stack, you're using it because you need that FILO behavior, not because you need a general purpose container.

If you need a random access container, use a random access container.
Ah, but is this the same as the stack when talking about the 'stack and heap' in regards to memory allocation of C++ in general?
C++ doesn't really have the concept of heap and stack in that context. We have variables of static storage duration, automatic storage duration, dynamic storage duration, and since C++11 thread storage duration.

Generally, the concept of heap and stack memory would refer to the areas of dynamic storage and automatic storage, respectively. It isn't really useful to think of these as "containers." They're just areas of memory where variables are stored, which differ in the manner that duration is determined.

The reason it's called the 'stack' is undoubtedly related to the way it allocates and reclaims memory, which very much resembles how a stack data structure works.
Topic archived. No new replies allowed.