Reputation: 1958
The following is probably not platform-dependent, but I'll fix it at Win 10 GCC in any case.
Suppose you create an array or vector, consisting of elements that each can be variable-sized, in static memory space in main():
RADIAL_UNITS = 1000000;
static vector<Pearl> necklace[RADIAL_UNITS] = { };
//each element is a variable-sized vector, which can consist of anywhere from 1-50 Pearl objects
or allocated on the stack in main() (assuming the stack space is set to allow at least 1000000 memory addresses):
vector<Pearl> necklace[RADIAL_UNITS] = { };
I'm assuming that, at runtime, necklace
consists of RADIAL_UNITS
contiguous memory addresses, pointing to the vector<Pearl>
elements. What's not clear to me is in (i) which memory space the vector elements reside (I'm suspecting the heap space).
Side questions I'm interested in as well:
It's also not clear to me (ii) how the compiler knows that the elements are variable sized. Do the STL containers have something defined internally that communicates this? If they were fixed sized, I'm assuming they would literally be contiguously present in whatever region we allocated the array to (the second case, i.e., allocation on the stack , would probably result in a segfault unless the default stack space in enlarged). (iii) Is it possible for me to fix the vector elements at size 50*sizeof(Pearl)
in order to allocate them in the same memory space the array was originally defined as? Pearl types consist of two flating point numbers, so they are of fixed size.
Upvotes: 4
Views: 151
Reputation: 726559
What's not clear to me is in which memory space the
vector
elements reside
Regardless of the space in which the vector
itself is allocated (a fixed-size data structure for tracking elements in its variable-length array) the elements of vector
always reside in dynamic memory, commonly known as "the heap".
It's also not clear to me how the compiler knows that the elements are variable sized. [...] If they were fixed sized, I'm assuming they would literally be contiguously present in whatever region we allocated the array to.
vector
object itself has fixed size. It serves as an "anchor" for a variable-sized array, which is always allocated dynamically. No special treatment is needed from the compiler.
Is it possible for me to fix the vector elements at size
50*sizeof(Pearl)
You cannot do it with vector
, but array
lets you do it:
static array<Pearl,50> necklace[RADIAL_UNITS];
Upvotes: 5