Mare Sorin-Alexandru
Mare Sorin-Alexandru

Reputation: 174

I want to declare a pyramid like structure in C++ in a particular way but cannot

I am essentially trying to declare something like this but I am unable to because of "too many initializer variables".

int** a = { {1},{2,3},{3,4,5} };

As a side question, if this were to work with some slight modification would it have the size of 9 (3x3) or 6 (1+2+3)?

I can implement this behavior with vectors such as the following, but I am curious as to why can't I do it more directly.

vector<int*>a = vector<int*>();
for (int i = 0; i < 20; i++)
{
    a.push_back(new int[i]);
    for (int j = 0; j <= i; j++)
        a[i][j] = i+j;
}

Upvotes: 2

Views: 146

Answers (1)

Michael Chourdakis
Michael Chourdakis

Reputation: 11158

Using a double pointer in C++ statically has a different memory arrangement than using new dynamically. The difference is that a static ** takes continuous memory automatically at compile time, where a dynamic one will not. Static multidimensional arrays are stored continuously, as discussed here.

Related: my question here.

Since your array cannot be stored continuously, it cannot be declared statically.

Upvotes: 1

Related Questions