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

C++ What's the problem in this line? int [] a = new int[size];

As the title suggests,

int [] a = new int[size];

constantly throws me an error.
I am not yet familiar with C++ so please help me tweak the code above to as closely similar to the syntax above (above was a given pseudo(?) code in a class) so I can create an array.

Thank you.

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

#include <iostream>
using namespace std;

// Test program
int main( )
{

    int [] a = new int[10];
    cout << a[0];

    return 0;
}

Tried running the above code and it failed to compile.

>Solution :

new is for dynamic allocation (of an array on the heap in this case), and returns a pointer to the new array.

[] in the declaration are for declaring it to be a stack array (and the brackets belong the right side of the variable name).

So the two legal approaches your code is mixing would simplify to either:

int a[10];  // Declares a stack array of size 10

or:

int *a = new int[10];  // Dynamically allocates a heap array of size 10 and stores the pointer to it in `a`

The former is the better solution here (there’s no benefit to a heap allocation for such a small array that is only used within the scope of this function, and it would require explicit delete[] a; later to properly clean it up).

That said, neither version initializes the values, so the contents of a[0] are uninitialized, and reading from them will get random garbage. Both versions can be changed to initialize the data with zeroes though, e.g.:

int a[10] = {0};  // Declares a stack array of size 10 and initializes to zero

or:

int *a = new int[10]();  // Dynamically allocates a heap array of size 10 and stores the pointer to it in `a`, initializing to zero

Final note: Using raw new is generally frowned upon in modern C++. If you needed heap-allocated contiguous data storage, you’re probably better off using 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