How are dynamic arrays are stored in memory?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • KioKrofov
    New Member
    • Jun 2008
    • 7

    How are dynamic arrays are stored in memory?

    Hello,

    I am trying to find out how Dynamic Arrays are actually stored in memory. Really, I want to know how Vectors are stored in memory, but I deduce they are stored the same way.

    If you have a dynamic array initialized at size 50, and it then needs to increase to size 75, what happens?

    Does element 49 contain some sort of pointer to the next 25 elements, or are a new 75 consecutive spots in memory allocated, and then the first 50 elements are copied into this new block of 75 elements?

    I have already done much research, and thus far what I find tells me how to initialize and use dynamic arrays within a program, but does not explain what is actually going on in memory.

    Thanks so much
  • pootle
    New Member
    • Apr 2008
    • 68

    #2
    Hi,

    Well for std::vector, instances are stored as a contigous block. When you create a vector, it reserves enough memory to store some number of instances (usually 20 by default). Then when you hit the capacity the vector is resized to allocate another chunk - by default this usually doubles the vector capacity. You can override the default behaviour, in the simplest form by using the reserve method, or you can provide a custom allocator as a template argument to containers.

    As for dynamic arrays, the elements themselves should be in a contiguous block too - as long as new has not been overloaded.... In a debugger, try looking at the address of each element.

    As a side issue, I would stay well clear of dynamic arrays if you can and would opt for a vector every time...

    HTH.

    Comment

    Working...