dynamic arrays?

Hello all

I have a question regarding arrays. Do you have to define their size during development, or can you dynamically allocate them?

I've came across vectors and it seems to do what I want, however I don't know if there intention is to be dynamic arrays or if there is another purpose for them?

Thanks

Ben
Yes ofc you can dynamically allocate them, in which point you wouldnt need the size defined at compile time (development?).

http://www.cplusplus.com/doc/tutorial/dynamic/

Vectors are great. They're pretty much like dynamic arrays, they can resize etc. They also keep track of their own size which is very handy.
Thanks.

Why would you ever use a dynamic array over a vector?
Why would you ever use a dynamic array over a vector?

You wouldnt.
Ok. so here's a question...

should I learn how to use dynamic arrays, or should I just carry on using vectors?
Dynamic arrays should be avoided. The keyword new and delete should be avoided, if you ever need to allocate memory use smart pointers (you can google that). Use vectors.
Why would you ever use a dynamic array over a vector?


When you work with legacy code and you have to use good old C.
You use dynamic arrays when you manually want to manage your memory. C++ has a lot of built-in features to make this a lot safer. You can forget to free your memory, causing a memory leak, or free it twice, causing a double-free (and probably a crash). C++ abstracts most of this away from you, so you don't have to bother using it yourself.

There are of course cases where you do need to use dynamic memory, think about creating large fixed-size buffers (for example to hold textures for a game). Usually you wrap the obtained pointer to the dynamic memory in a smart pointer then, a smart pointer will automatically free the memory when it is no longer required (when all of its pointers go out of scope).

Of course, when you want to pass the memory to C or assembly, you will need to use a raw pointer (which can also be obtained from a smart pointer, in case C doesn't use the pointer after the smart pointer frees it), but in this scenario, it is also possible to just pass a pointer to the first element of a vector (as long as the C code treats it as a fixed-size array).
Last edited on
Thanks for the replies guys. Much appreciated.
Hm what makes you say you shouldn't use dynamic arrays or new or delete?

These are all common functions in C++, why do you say you should avoid using these methods?
Topic archived. No new replies allowed.