What exactly does it meant to be a dynamic array? I know it means malloc, but what is different about a dynaic array versus a (I presume?) static one?
What exactly does it meant to be a dynamic array? I know it means malloc, but what is different about a dynaic array versus a (I presume?) static one?
Dynamic memory is memory that was allocated in addition to the memory your program was initially given by the OS. So, essentially, it just means malloc.
It doesn't mean that can just resize the array willy-nilly (although're there's realloc), but what's nice is that since it's just a pointer you're using, you can free() that pointer and than use it for something else, or for an array of a different size. That's what make it dynamic.
You could go to (say) dictionary.com to find the difference in meaning of the two words.
Dynamic memory is the storage that is allocated at runtime.
Thanks Sean
tabstop - i know the difference in the definition, I am looking for a definition in a specific context. No need to be a smartass.
Dynamic refers to it having varying sizes throughout its lifetime - presumably governed by user input or some other external data. The program is expected to accommodate such an array - but usually there is at least some additional knowledge required such as the maximum expected size.
I might as well take a stab at it too:
Dynamic memory is allocated on the heap by a program at runtime. It has several advantages over e.g. automatic variables declared in stack memory.
- The amount of memory that you dynamically allocate can be determined at runtime. As mentioned by nonoob, this means that you can e.g. allocate just enough memory to store external data. With an array, you'd have to put an upper limit on the size and usually waste space, as well as running the risk of hitting the upper limit.
- The heap has a lot more space than the stack does. If you need 200MB of memory for an expensive calculation, you can probably get it with malloc(); you certainly couldn't fit it onto the stack under most circumstances.
Of course, dynamic memory has its drawbacks. You have to free it manually (though sometimes this is an advantage, if different sections of code need to use the same memory); stack memory is automatically freed for you. Plus your program might fail to get heap memory.
All in all, though, dynamically allocated memory is a lot more flexible and useful.
dwk
Seek and ye shall find. quaere et invenies.
"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell
Other boards: DaniWeb, TPS
Unofficial Wiki FAQ: cpwiki.sf.net
My website: http://dwks.theprogrammingsite.com/
Projects: codeform, xuni, atlantis, nort, etc.
Although "stack" and "heap" are implementation concepts and not C concepts.