Trismegistos
Trismegistos

Reputation: 3882

Define 2d array with dynamic first dimension and static second in c++

I would like to define int array in which first dimension is choosen dynamically but second is static -- something like int array[][8]. Unfortunatelly I can not allocate such array dynamically. int ary[][8] = new int[11][8]; Produces error:

error: initializer fails to determine size of ‘array’
    6 |     int array[][8] = new int[11][8];
      |                      ^~~~~~~~~~~~~~
2d.cpp:6:20: error: array must be initialized with a brace-enclosed initializer

or when I try following code:

int array[][8] = new int*[11];
array[0] = new int[8];

I get

2d2.cpp:6:22: error: initializer fails to determine size of ‘array’
    6 |     int array[][8] = new int*[11];
      |                      ^~~~~~~~~~~~
2d2.cpp:6:22: error: array must be initialized with a brace-enclosed initializer
2d2.cpp:7:25: error: incompatible types in assignment of ‘int*’ to ‘int [8]’
    7 |     array[0] = new int[8];

Is that even possible in c++?

Upvotes: 0

Views: 198

Answers (2)

Trismegistos
Trismegistos

Reputation: 3882

I will answer my own question:

int (*array)[8] = new int[11][8];

I forgot how bad C++ rules for creating type definitions -- especially including pointers, arrays and function pointers -- are. I added missing parentheses around array and now it is fine.

Upvotes: 1

Daniel
Daniel

Reputation: 8441

Just use std::vector and std::array:

#include <vector>
#include <array>
#include <iostream>

int main()
{
    using MyArray = std::vector<std::array<int, 8>>;
    MyArray arr {11};
    for (int i {0}; i < 8; ++i)
        arr[i][i] = i;
    for (const auto& v : arr) {
        for (auto x : v) {
            std::cout << x << " ";
        }
        std::cout << std::endl;
    }
}

Live On Coliru

Upvotes: 1

Related Questions