Aparajithan Venkateswaran Aparajithan Venkateswaran - 3 months ago 13
C++ Question

How to initialize a dynamically sized array in C++11 standard?

This is my piece of code.

int** n;
for (int i = 0; i < N; ++i){
int size;
cin >> size;
int* n[i] = new int[size]; //line 13
for (int j = 0; j < size; ++j){
cin >> n[i][j];
}
}


This is the error that pops up during compilation.


solution.cc: In function 'int main()':

solution.cc:13:33: error: array must be initialized with a brace-enclosed initializer

int* n[i] = new int[size];


I realise that this can be done using vectors since they are so much better at handling memory dynamically. But I am not allowed to use vectors for this challenge. The only header I am allowed to use is "iostream".

I read that, in C++11, the syntax has been modified for new:

p = new T [N] {initializer1, ..., initializerN};


Source: https://en.wikipedia.org/wiki/New_and_delete_(C%2B%2B)#Overview

But my code still produces the same error for similar variants.

Is there a way to bypass the initialization error totally? If not, assume that the values are initialized to, preferably, the same value.

Answer

I believe (IMHO) you are not looking to the real problem.

You have declared a double pointer:

int** n;

Then you forget to allocate memory for the array of pointers, something like:

n = new int*[N]

This step is necessary before you can allocate memory for each pointer of your array (of pointers).

Moreover, I believe that your line should be:

n[i] = new int[size]

else you are redeclaring the type of n+i.

Comments