Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do they declare dynamic arrays this way, if it doesn't seem necessary?

I saw on the internet and was told in uni, that you should specify array’s size, when declarin this way: int* array = new int(size);
(example from the internet)

Hovever, doesn’t this line simply apply a value to the address, that was created?

In other words,this is just after declaration and this is when I filled the array (even further, than I should have, by logic)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why so? Are dynamic arrays a good practice at all? They don’t seem reliable

as described above…

>Solution :

You have been told wrong, the correct way is

int* array = new int[size];

Use [] not ().

Your version allocates a single int not an array, and, as you have observed, initialises the integer to the given value.

In general new T[size] allocates an array of T of the given size, and calls the default T constructor for each element. Whereas new T(args, ...) allocates a single T and calls the T constructor with the given arguments.

On the final point, you should rarely use dynamic arrays in C++, almost always the correct thing to use in their place is a std::vector.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading