Home > Back-end >  C What's the problem in this line? int [] a = new int[size];
C What's the problem in this line? int [] a = new int[size];

Time:12-01

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.

#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.

CodePudding user response:

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.

  • Related