You use a dynamic container when your data is dynamic, or you need to transfer data from different areas of your program.
1 - Dynamic data Say you have a list of your neighbors. They are building a new house on your street, and you should add a guy to the list, but you have been allocated enough space for 15 neighbors. This dynamic memory will allow you to increase the size of this container. This is not how it works. In fact, it finds a new piece of memory of the required size and then copies the old container.
Or another example. Say you are writing a program that tracks an address book. One of your users has ten contacts. The other user is a corporation, and 50,000 employees must be stored in this address book. You do not want to highlight 50,000 spaces for a user who has ten contacts, so you specify exactly how much you need.
2 - Data Transfer When you allocate static data, it is pushed onto the stack and then inaccessible after exiting the scope. Therefore, if you call some function that generates your array and then passes the memory address of the array back to your caller, you will get a runtime error. This is due to the fact that after this function exits, the array goes out of scope, and therefore it is removed from the stack.
However, if you allocate it dynamically, it goes into a heap and is not freed until you release it or until the program exits. That way, you can simply save the pointer to the beginning of the array and use it throughout your program, without worrying that it goes out of scope until you want it.
source share