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

Initialize array on the heap without specifying its length

I was reading Bjarne Stroustrup’s Programming Principles and Practice Using C++ (second edition). On page 597:

double* p5 = new double[] {0,1,2,3,4};

…; the number of elements can be left out when a set of elements is provided.

I typed the code above into Visual Studio 2022, and I get red underlines saying that "incomplete type is not allowed" (same thing happens when I define p5 as a data member), nevertheless, the code compiles and runs successfully.

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


May I ask if it is fine to define array in such way? If so, why would Visual Studio show those red underlines…?

>Solution :

May I ask if it is fine to define array in such way?

Yes, starting from C++11 it is valid. From new expression’s documentation:

double* p = new double[]{1,2,3}; // creates an array of type double[3]

This means in your example,

double* p5 = new double[] {0,1,2,3,4};

creates an array of type double[5]

Demo


Note

This is p1009r2.

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