What are the advantage do you have using dynamic memory allocation over static memory?
Static allocations are only useful when you know precisely the
type and number of variables your program will use. While fixed
size arrays of any size can certainly be allocated statically, the
only way you can allocate a variable length array statically is by
allocating more memory than you will ever use even in the worst
case scenario. This is clearly impractical since some of that
memory will never be used at all and most of it will only seldom be
used.
Local variables, on the other hand, make use of the current
thread's stack to improve memory consumption, instantiating
variables on an as-required basis with very little cost in terms of
performance. However, unlike static memory, the call stacks have
very limited capacity and are therefore unsuitable for large data
structures, particularly variable length structures. Thus it makes
more sense to dynamically allocate variable length arrays on the
heap. The only real cost is in terms of the physical allocation
but, once allocated, there is no difference in terms of access
times compared to static or stack memory. It is all the exact same
memory after all.