2

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;
}
  • You could use a vector, and calculate the index from the "tier" and "position-in-tier" by `int index(int tier, int position) { return (tier * (tier + 1) / 2) + position; }` – Eljay May 19 '20 at 19:06

1 Answers1

1

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.

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78
  • Is there a reason as to thy it cant be stored continuously as in {1,2,3,4,5,6} ? Is it something that just isn't done ? I have looked at the links but couldn't understand everything. – Mare Sorin-Alexandru May 19 '20 at 18:58
  • 1
    @Skcoica You can do that. You make a single 1d array and perform the indexing math yourself, though I recommend making a wrapper class to help you avoid code duplication from scattering the indexing math all over your code. [Here is a simple example using a `std::vector`](https://stackoverflow.com/a/2076668/4581301) and [here is a much more complicated example using `new`](https://isocpp.org/wiki/faq/operator-overloading#matrix-subscript-op) – user4581301 May 19 '20 at 19:08