Apara
Apara

Reputation: 374

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.

Upvotes: 2

Views: 2267

Answers (3)

ZerosAndOnes
ZerosAndOnes

Reputation: 1093

This should solve your problem.

int** n = new int*[N];

for (int i = 0; i < N; ++i){
    int size;
    cin >> size;
    n[i] = new int[size];

    for (int j = 0; j < size; ++j){
        cin >> n[i][j];
    }
}

Upvotes: 6

Emilio Pastor Mira
Emilio Pastor Mira

Reputation: 350

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.

Upvotes: 12

Igor Tandetnik
Igor Tandetnik

Reputation: 52591

Do yourself a favor and stop using raw pointers. Use std::vector in place of raw arrays whenever possible - something along these lines:

std::vector<std::vector<int>> n(N);
for (int i = 0; i < N; ++i){
    int size;
    cin >> size;
    n[i].resize(size);
    for (int j = 0; j < size; ++j){
        cin >> n[i][j];
    }
}

Upvotes: 2

Related Questions